'How to handle exceptions in spring web flux functional end point?
I want a global exception handler for the inputs in spring boot web flux functional end point.
I have written exception class by extending runtime exception and handler with @component scan. My problem is even though an exception occurred handler will not handle it.
Exception class
@ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
@Data
public class InputValidationException extends RuntimeException{
private final String input;
private static final int errorCode = 400;
public InputValidationException(String message, String input) {
super(message);
this.input = input;
}
}
Exception Handler Class
@ControllerAdvice
public class InputValidationExceptionHandler {
@ExceptionHandler(InputValidationException.class)
public ResponseEntity<InputValidationResponse> handleException(InputValidationException ex) {
InputValidationResponse response = new InputValidationResponse();
response.setErrorCode(ex.getErrorCode());
response.setMessage(ex.getMessage());
response.setInput(ex.getInput());
return ResponseEntity.badRequest().body(response);
}
}
My functional end point
@RouterOperation
@Bean
public RouterFunction<ServerResponse> userForgetPassword(UserHandler handler){
return RouterFunctions.route().
POST("/api/users/forgetPassword/{email}",
accept(APPLICATION_JSON), handler::sendOtp)
.onError(InputValidationException.class,sendOtpExceptionHandler())
.build();
}
public BiFunction<Throwable, ServerRequest, Mono<ServerResponse>> sendOtpExceptionHandler(){
return (err, req)->{
InputValidationException ex = (InputValidationException) err;
InputValidationResponse response = new InputValidationResponse();
response.setInput(ex.getInput());
response.setMessage(ex.getMessage());
response.setErrorCode(ex.getErrorCode());
return ServerResponse.badRequest().bodyValue(response);
};
}
Service method
public Mono<Object> sendOtp(String email){
Mono<String> otpMono = generateOtp();
return patternMatches(email,EMAIL_REGEX)
.handle((valid, sink) -> {
if(valid)
sink.next(email);
else
sink.error(new InputValidationException("Email not valid", email));
})
Response of the API
{
"timestamp": 1652806523422,
"path": "/api/users/forgetPassword/lakmaldasun2011",
"status": 400,
"error": "Bad Request",
"requestId": "845f18f6-1"
}
Can anyone tell me what is the problem here to not to handle the exception?
Thanks.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
