Last active
June 16, 2022 14:01
-
-
Save artemptushkin/964e7621c9b3eb0b340364f8b8f335e0 to your computer and use it in GitHub Desktop.
servlet-exception-handler
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
@Slf4j | |
@ControllerAdvice | |
@Profile("servlet") | |
@RequiredArgsConstructor | |
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) | |
public class ServletExceptionHandler { | |
private final Map<Class<? extends Exception>, HttpStatus> exceptionToStatusCode; | |
private final HttpStatus defaultStatus; | |
@ExceptionHandler(CustomExceptionInFilter.class) | |
public ResponseEntity<ErrorResponse> handleCustomException(CustomExceptionInFilter ex) { | |
return this.handleException(ex); | |
} | |
@ExceptionHandler(Exception.class) | |
public ResponseEntity<ErrorResponse> handleException(Exception ex) { | |
HttpStatus status = exceptionToStatusCode.getOrDefault(ex.getClass(), defaultStatus); | |
ErrorResponse errorResponse = ErrorResponse | |
.builder() | |
.message(ex.getMessage()) | |
.code(status.value()) | |
.build(); | |
log.error("Exception has been occurred", ex); | |
return new ResponseEntity<>(errorResponse, status); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment