Вы можете расширить ResponseEntityExceptionHandler
с помощью аннотации @ControllerAdvice
. Это захватит исключение, и вы можете обработать и отправить пользовательский ответ. Пример:
@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(CustomExceptionHandler.class);
public CustomExceptionHandler() {
}
// overriding an exception that already is been handled in ResponseEntityExceptionHandler
@Override
protected ResponseEntity<Object> handleMissingPathVariable(MissingPathVariableException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
log.warn(ex.toString());
final String parameter = ex.getParameter().getParameterName();
final String detailMessage = ex.getMessage();
final String message = "Parameter " + parameter + " is missing.";
final ErrorMessageDTO result = new ErrorMessageDTO(HttpStatus.BAD_REQUEST, message, parameter, detailMessage, null);
return ResponseEntity.badRequest().body(result);
}
// Custom handle to intercept BadCredentialsException
@ExceptionHandler(BadCredentialsException.class)
@ResponseBody
ResponseEntity<Object> handleBadCredentialsException(HttpServletRequest req,
BadCredentialsException ex) {
log.warn(ex.toString());
final ErrorMessageDTO result = new ErrorMessageDTO(HttpStatus.UNAUTHORIZED, ex.getMessage());
return ResponseEntity.badRequest().body(result);
}
}