How to catch global exceptions in Spring Boot?

In Spring Boot, you can capture global exceptions by either implementing the ErrorController interface or using the @ControllerAdvice annotation.

Option 1:
Option 1: Implementing the ErrorController interface.

  1. Controller for managing errors
  2. retrieveErrorPath
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class CustomErrorController implements ErrorController {

    @Override
    public String getErrorPath() {
        return "/error"; // 定义错误页面的路径
    }

    @RequestMapping("/error")
    public String handleError() {
        // 处理异常的逻辑
        return "error"; // 返回错误页面
    }
}
  1. properties file for an application
  2. YAML file for the application

Option 2: Utilize the @ControllerAdvice annotation.

  1. @ControllerAdvice is an annotation in Spring Framework used for global exception handling and applying common behavior to multiple controllers.
  2. When an exception is caught/not handled
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ModelAndView handleException(Exception e) {
        // 处理异常的逻辑
        ModelAndView mav = new ModelAndView();
        mav.addObject("errorMsg", e.getMessage());
        mav.setViewName("error"); // 返回错误页面
        return mav;
    }
}
  1. properties file for the application
  2. configuration file for an application

Both methods mentioned above can capture global exceptions and return custom error pages or error messages.

bannerAds