Add global exception management in Rest web service

Since I adopted a Restful architecture, I need also a simple way for the exceptions management.
With Spring, it can be easily set-up with in a central class, avoiding a painful management per service.

To do this, we need to define a class with the @ControllerAdvice annotation, this class will be automatically associated to our controllers during the classpath scanning. By default, it will be added to all controllers found, I decided to restrict to our concerned classes by specifying the controller’s package.

package net.classnotfound.exception.handler;

import[...]

@ControllerAdvice(basePackages = {"net.classnotfound.controller" })
class ControllerExceptionHandler {

    private static final Logger LOG = LoggerFactory.getLogger(ControllerExceptionHandler.class);

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    String handleNullRequest(final HttpServletRequest req, final RuntimeException ex) {
        LOG.error(ex.getLocalizedMessage(), ex);
        return ex.getLocalizedMessage();
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(Exception.class)
    @ResponseBody
    String handleBadRequest(final HttpServletRequest req, final Exception ex) {
        LOG.error(ex.getLocalizedMessage(), ex);
        return ex.getLocalizedMessage();
    }

}

The @ExceptionHandler defines the method as a specific handler for the type of exception, we have to use the same type of exception in the method signature.
The @ResponseStatus indicates which HTTP status is returned for this particular type of exception.

One thought on “Add global exception management in Rest web service”

Leave a Reply

Your email address will not be published. Required fields are marked *


Time limit is exhausted. Please reload CAPTCHA.