Skip to content

Global Exception Handler

mangeshdase edited this page Oct 29, 2021 · 1 revision

Description

Exception handling is one of the most important features of any Software application, either a monolithic web or REST full API or microservice. Certainly, we will not want our end-users to see a long error stack trace of null pointer exception or any database exception which is just meaningless and annoying to a very laymen users. Even you are an experienced developer and trying to call a third party REST API and something goes wrong, you must be figure out from the JSON response, what actually is happening under the hood.

Difference between local exception handling vs global exception handling

In SpringBoot the request is handled by Controller classes method - if any error occurred in any particular method of the controller class then it can be handled in that @Controller class only. This is the local exception handling.

Alternatively we can have Multiple @Controller class throwing the same kind of exception, grouping them, and handling them by the group can be called global exception handling.

Advantage

The advantage of global exception handling is all the code necessary for handling any kind of error in the whole of our application can be separated and modularized.

Implementation

In that project we use @ControllerAdvise annotation which can be used to handle exception globally. So, we Create a class ExceptionTranslator.java with @ControllerAdvise annotation. In that class we use @ExceptionHandler annotation with different types of exceptions for different controllers.

Code Snippets

@ControllerAdvice
public class ExceptionTranslator implements ProblemHandling, SecurityAdviceTrait {
private static final String FIELD_ERRORS_KEY = "fieldErrors";
private static final String MESSAGE_KEY = "message";
private static final String PATH_KEY = "path";
private static final String VIOLATIONS_KEY = "violations";
@Value("${jhipster.clientApp.name}")
private String applicationName;
private final Environment env;
public ExceptionTranslator(Environment env) {
    this.env = env;
}

In that we use @ExceptionHandler annotated method for each Controller, as shown below we create a method handleEmailAlreadyUsedException() for EmailAlreadyUsedException.

@ExceptionHandler
public ResponseEntity<Problem> handleEmailAlreadyUsedException(
    EmailAlreadyUsedException ex,
    NativeWebRequest request
) {
    EmailAlreadyUsedException problem = new EmailAlreadyUsedException();
    return create(
        problem,
        request,
        HeaderUtil.createFailureAlert(applicationName, false, problem.getEntityName(), problem.getErrorKey(), problem.getMessage())
    );
}

Clone this wiki locally