Sunday, 20 May 2018

Handle Exception in SpringBoot

In SpringBoot, how to handle exceptions?

Before 3.2,


1. The controller level @ExceptionHandler

drawback: it is defined within a controller, and it works only for that controller.

2. The HandlerExceptionResolver:

It offers a uniform exception handler, which is enabled by default Dispatch servlet.

@ExceptionHandler: since Spring 3.1
@ResponseStatus: since Spring 3.0, it is a ResponseStatusExceptionResolver, mapping an Exception to a HttpStatus code.

drawback: 1) it maps an exception to an HTTP status code in the response but without a body massage. 2) one ResponseStatus is able to handle only one Exception.

3. The new one:  @ControllerAdvice
Since Spring 3.2 above, it allows scattered handlers resided in one handler, and it allows to customize response body.


Reference:
Error Handling for REST with Spring


No comments:

Can Jackson Deserialize Java Time ZonedDateTime

Yes, but must include JSR310. Thus ZonedDateTime can be deserialized directly from JSON response to POJO field. <dependency> <g...