Spring Boot Exception Handling — HandlerExceptionResolver.

Spring Boot Exception Handling — HandlerExceptionResolver.

Getting Started:

Error and Exception handling is essential and important for application development and proper responses with reasonable details are required for better debugging and user experience. Whether you are a mobile, web, API, Desktop, or enterprise application developer then you need to handle exceptions properly and display to the end-user proper messages.

Spring Boot provides a /error endpoint mapping that handles all errors in a sensible way, and it is registered as a “global” error page in the servlet container. If you are implementing a REST API or a web application with a UI template using spring boot you will get a proper JSON or HTML view rendered. You will have the option to change this template using different methods.

Spring framework allows you to handle the exceptions using different ways either it could be at the application level or controller level. You can use this technique to prepare the proper response with the proper status codes.

  1. @ControllerAdvice and @ExceptionHandler.
  2. Using HandlerExceptionResolver.
  3. Using ResponseStatusException.

HandlerExceptionResolver Interface to be implemented by objects that can resolve exceptions thrown during handler mapping or execution, in the typical case to error views. Implementors are typically registered as beans in the application context.

Example:

As I said earlier you have to implement the interface with the concrete implementation of method resolveException. The return type of this method is a ModelAndView object and you will have access to the request, response, and exception object instances.

@Component
class APIResponseExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(
           HttpServletRequest request, 
           HttpServletResponse response, 
           Object object, 
           Exception exception) {
        ModelAndView model = new ModelAndView();
        model.setView(new MappingJackson2JsonView());
        model.addObject("exception", exception.getMessage());
        return model;
    }

}

If you want to have different logic for different types of exceptions or custom exceptions you can use the instanceof keyword to check the type of exception and return the proper error message, code, and view.

if( exception instanceof ArithmeticException ){
    ModelAndView model = new ModelAndView();
    model.setView(new MappingJackson2JsonView());
    model.addObject("exception", exception.getMessage());
    return model;
}

Above code snippet, if in case you are returning the JSON response but if you want to return view like HTML page.

model.setView("errors/http-exception.html");

Now your code is ready to handle the exception but to make this actionable you have to register or configure this resolver to WebMvcConfigurer.

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void configureHandlerExceptionResolvers(
             List<HandlerExceptionResolver> resolvers) {
        resolvers.add(0, new APIResponseExceptionResolver());
    }

}

Once everything is configured properly then if any exception occurs in your application, you will get a response in proper JSON format.

{
  "arithmeticException": {
      "cause": null,
      "stackTrace": [],
      "localizedMessage": "Sum is divided by zero!",
      "message": "exceptional arithmetic condition has occurred check input numbers ",
      "suppressed": []
  }
}

Conclusion:

In this article, you are able to learn the one way of handling exceptions in spring boot and returning the meaningful message or user-readable and understandable message to the end-user. Whether you are an API developer or developed a spring boot web application you are able to return error messages in JSON format or return views that will display meaningful messages.

More such articles:

https://medium.com/techwasti

https://www.youtube.com/channel/UCiTaHm1AYqMS4F4L9zyO7qA

https://www.techwasti.com/

==========================**=========================

If this article adds any value for you then please clap and comment.

Let’s connect on Stackoverflow, LinkedIn, & Twitter.

Did you find this article valuable?

Support techwasti by becoming a sponsor. Any amount is appreciated!