Search results
Spring Boot APIs @ControllerAdvice vs @RestControllerAdvice
@RestControllerAdvice = @ControllerAdvice + @ResponseBody.
@ControllerAdvice
ControllerExceptionAdvice.java
:
@ControllerAdvice
public class ControllerExceptionAdvice {
@ExceptionHandler({
ConstraintViolationException.class,
DataIntegrityViolationException,
IllegalArgumentException
})
@ResponseBody
public ResponseEntity<Error> invalidRequestHandler(RuntimeException ex) {
// ...
return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
}
// ...
}
@RestControllerAdvice
RestControllerExceptionAdvice.java
:
@RestControllerAdvice
public class RestControllerExceptionAdvice {
@ExceptionHandler({
ConstraintViolationException.class,
DataIntegrityViolationException,
IllegalArgumentException
})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Error invalidRequestHandler(RuntimeException ex) {
Error error = Error.builder()
.timestamp(new Date())
.message(ex.getMessage())
.build();
return error;
}
// ...
}
Also related to this page:
Recipe to handle Spring Boot RESTful Controller Exceptions with @ControllerAdvice
Recipe to handle Spring Boot RESTful Controller Exceptions with @ControllerAdvice