Created
June 14, 2022 11:45
-
-
Save artemptushkin/4cd1cd8420ad7ff94d85ba5fae456064 to your computer and use it in GitHub Desktop.
reactive-global-exception-handler.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ReactiveExceptionHandler extends AbstractErrorWebExceptionHandler { | |
private final Map<Class<? extends Exception>, HttpStatus> exceptionToStatusCode; | |
private final HttpStatus defaultStatus; | |
public ReactiveExceptionHandler(ErrorAttributes errorAttributes, WebProperties.Resources resources, | |
ApplicationContext applicationContext, Map<Class<? extends Exception>, HttpStatus> exceptionToStatusCode, | |
HttpStatus defaultStatus) { | |
super(errorAttributes, resources, applicationContext); | |
this.exceptionToStatusCode = exceptionToStatusCode; | |
this.defaultStatus = defaultStatus; | |
} | |
@Override | |
protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) { | |
return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse); | |
} | |
private Mono<ServerResponse> renderErrorResponse(ServerRequest request) { | |
Throwable error = getError(request); | |
log.error("An error has been occurred", error); | |
HttpStatus httpStatus; | |
if (error instanceof Exception exception) { | |
httpStatus = exceptionToStatusCode.getOrDefault(exception.getClass(), defaultStatus); | |
} else { | |
httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; | |
} | |
return ServerResponse | |
.status(httpStatus) | |
.contentType(MediaType.APPLICATION_JSON) | |
.body(BodyInserters.fromValue(ErrorResponse | |
.builder() | |
.code(httpStatus.value()) | |
.message(error.getMessage()) | |
.build()) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment