Skip to content

Instantly share code, notes, and snippets.

@artemptushkin
Last active June 16, 2022 14:01
Show Gist options
  • Save artemptushkin/964e7621c9b3eb0b340364f8b8f335e0 to your computer and use it in GitHub Desktop.
Save artemptushkin/964e7621c9b3eb0b340364f8b8f335e0 to your computer and use it in GitHub Desktop.
servlet-exception-handler
@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