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.
- Controller for managing errors
- 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"; // 返回错误页面
}
}
- properties file for an application
- YAML file for the application
Option 2: Utilize the @ControllerAdvice annotation.
- @ControllerAdvice is an annotation in Spring Framework used for global exception handling and applying common behavior to multiple controllers.
- 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;
}
}
- properties file for the application
- configuration file for an application
Both methods mentioned above can capture global exceptions and return custom error pages or error messages.