1

Similar to the support for bean validation using @Valid, @Validated, @ExceptionHandler annotations available in spring boot REST APis, is similar support available for spring cloud function? If yes, could you please direct me to a working example on how to do this?

For REST APIs using spring boot web, we would do something like below -

#Controller

public Response execute (@RequestBody @Valid Request req) {

}

@ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(code = HttpStatus.OK)
    public Response handleMethodArgumentNotValid(MethodArgumentNotValidException e) {
for (FieldError fieldError : e.getBindingResult().getFieldErrors()) {

}
}

#Model

public class Request {
@NotNull
private String name;
... and so on
}

While converting this app to spring cloud function, I have something like below -

@Bean
public Function<Request,Response> execute () {
 return req -> {
      return new Response();
} 
}

Is it possible to @Valid against the model (Request) while defining spring cloud function?

If so, how/where do we define @ExceptionHandler(MethodArgumentNotValidException.class) to catch the validation errors? Regards
Jacob

Jacob
  • 426
  • 3
  • 19

1 Answers1

0

Import the Validator with @Autowired, do the validation programmatically returning a Message.

@Autowired
Validator validator;

@Bean
Function<Request, Message<?>> processaReq() {
    return request -> processa(request);
}

private Message<?> processa(Request request) {
    Set<ConstraintViolation<Request>> constraintViolation = validator.validate(request);
    if (!constraintViolation.isEmpty()) {
       Message<ErrorResponse> message = MessageBuilder.withPayload(new ErrorResponse(constraintViolation.toString())).setHeader(FunctionInvoker.HTTP_STATUS_CODE, 404).build();
       return message;
    }

    Response response = new Response("Success");

    Message<Response> message = MessageBuilder.withPayload(response).setHeader(FunctionInvoker.HTTP_STATUS_CODE, 200).build();
    return message;
}

class ErrorResponse {
    private String message;

    public ErrorResponse(String message) {
       this.message = message;
    }
    // Puts gets and sets
}