🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
局部异常只在特定的地方使用,而不是全局,比如只在指定的 controller 层中使用。 <br/> 捕捉局部异常的步骤如下: **1. 在controller层中指定异常类型** ```java /** * 1. 该方法抛出RuntimeException异常 */ @RequestMapping("/v5/get/student") public String getStudent05() { int i = 0; if (i < 1) throw new RuntimeException("id不能小于1."); return "student"; } /** * 2. 注解@ExceptionHandler根据value指定的异常类型对当前的controller类发生的异常进行处理 */ @ExceptionHandler(value = {RuntimeException.class}) public String handlerException(RuntimeException ex, HttpServletRequest request) { request.setAttribute("ex", ex); //跳转到error.jsp页面 return "error"; } ``` **2. 视图层:`webapp/WEB-INF/views/error.jsp`** ```html <h1>---${ ex }---</h1> ``` **3. 测试** 启动项目访问 http://localhost:8080/mvc/v5/get/student 前端将会看到如下信息。 ``` ---java.lang.RuntimeException: id不能小于1.--- ```