When a MethodArgumentNotValidException
is thrown in my Spring app I would like the response to:
- Have a 400 code
- Have a body similar to the one you get when you throw a
ResponseStatusException
in a regular controller
Here's my code for now:
@ControllerAdvice
public class CustomExceptionHandlers extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
FieldError err = ex.getBindingResult().getFieldErrors().get(0);
String msg = "Unknown error";
if (err != null) {
msg = err.getField() ": " err.getDefaultMessage();
}
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, msg);
}
}
The problem is: it does nothing (I guess). I feel like I shouldn't throw an exception in a ResponseEntityExceptionHandler
.
Any idea?
Edit: Apparently I want what DefaultErrorAttributes
produces, but I still don't know how to use it.
CodePudding user response:
@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class CustomExceptionHandler {
@ResponseStatus(BAD_REQUEST)
@ResponseBody
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, Object>> methodArgumentNotValidException(MethodArgumentNotValidException ex, WebRequest request) {
// Make the message
FieldError err = ex.getBindingResult().getFieldErrors().get(0);
String msg = "Unknown error";
if (err != null) {
msg = err.getField() ": " err.getDefaultMessage();
}
// Set attributes
request.setAttribute("javax.servlet.error.status_code", BAD_REQUEST.value(), WebRequest.SCOPE_REQUEST);
request.setAttribute("javax.servlet.error.message", msg, WebRequest.SCOPE_REQUEST);
// Return the error
DefaultErrorAttributes errorAttributes = new DefaultErrorAttributes();
return ResponseEntity.badRequest().body(errorAttributes.getErrorAttributes(request, false));
}
}