Spring MVC提供了多种异常处理机制,以下是核心处理方式及实现方法:
一、局部异常处理(Controller级别)
- @ExceptionHandler注解
在Controller内部定义异常处理方法,捕获当前控制器抛出的指定异常。@Controller public class UserController { @GetMapping("/test") public String test() { if (true) throw new ArithmeticException("除零错误"); return "success"; } @ExceptionHandler(ArithmeticException.class) public String handleMathException(Exception ex, Model model) { model.addAttribute("error", ex.getMessage()); return "error-p