With Spring Boot 1.4+ new cool classes for easier exception handling were added that helps in removing the boilerplate code.
A new @RestControllerAdvice
is provided for exception handling, it is combination of @ControllerAdvice
and @ResponseBody
. You can remove the @ResponseBody
on the @ExceptionHandler
method when use this new annotation.
i.e.
@RestControllerAdvice
public class GlobalControllerExceptionHandler {
@ExceptionHandler(value = { Exception.class })
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ApiErrorResponse unknownException(Exception ex, WebRequest req) {
return new ApiErrorResponse(...);
}
}
For handling 404 errors adding @EnableWebMvc
annotation and the following to application.properties was enough:
spring.mvc.throw-exception-if-no-handler-found=true
You can find and play with the sources here:
https://github.com/magiccrafter/spring-boot-exception-handling