spring boot handlerexceptionresolver example 2017-04-19 09:04

There are many ways to handle the exception in Spring Boot. You can click Spring Boot exception handler example or Spring Boot global exception example to see how to handle exception in controller or handler. I will show you how to handle exception by implementing HandlerExceptionResolver.

The dependency is like following.


The structure of this project.

    │  └─com
    │      └─henryxi
    │          └─exception
    │              └─resolver
    │                      AppConfig.java
    │                      CustomException.java
    │                      MyExceptionHandler.java
    │                      SampleController.java


public class AppConfig {
    HandlerExceptionResolver customExceptionResolver () {
        return new MyExceptionHandler();
    public static void main(String[] args) throws Exception {
        SpringApplication.run(AppConfig.class, args);


public class CustomException extends Exception{

    private static final long serialVersionUID = 2490632169435714046L;

    public CustomException() {

    public CustomException(String message) {

    public CustomException(String message, Throwable cause) {
        super(message, cause);

    public CustomException(Throwable cause) {


public class MyExceptionHandler implements HandlerExceptionResolver {
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ModelAndView model = new ModelAndView();
        model.setView(new MappingJackson2JsonView());
        model.addObject("exception", ex.getMessage());
        return model;


public class SampleController extends SpringBootServletInitializer {

    public String exception() throws Exception {
        throw new Exception("this is exception");

    public String customException() throws Exception {
        throw new CustomException("this is custom exception");

Run the main method of AppConfig. Access "http://localhost:8090/custom-exception" and "http://localhost:8080/exception" to see the result.