六、SpringMVC的异常处理
6.1 SpringMVC异常概述
我们在处理异常时,通常使用try…catch块来处理程序中发生的异常;出现异常时每个过程都单独处理异常,系统的代码耦合度高,工作量大且不好统一,维护的工作量也很大。
SpringMVC提供的异常处理机制可以把异常处理抽离成方法、类;让处理异常的代码与我们的业务代码完全分开,降低与业务核心代码的耦合度;
6.2 SpringMVC异常处理
6.2.1 单个类处理方式
package com.dfbz.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/demo01")
public class Demo01Controller {
@RequestMapping("/demo01")
@ResponseBody
public String demo01(Integer flag) {
if (flag == 0) {
int i = 1 / 0;
}
return "success";
}
@ExceptionHandler(value = {ArithmeticException.class})
public String arithmeticExceptionHandler(Model model, Exception e) {
model.addAttribute("message",e.getMessage());
return "forward:/error.jsp";
}
@ExceptionHandler(value = {Exception.class})
public String exceptionHandler(Model model, Exception e) {
model.addAttribute("message", e.getMessage());
return "forward:/error.jsp";
}
}
6.2.2 处理全局异常
我们可以编写一个类实现实现HandlerExceptionResolver接口来处理全局异常
package com.dfbz.exception;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
@Component
public class MyExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
System.out.println(handler.getClass());
System.out.println(ex.getClass());
ModelAndView mv = new ModelAndView();
mv.addObject("message", ex.getMessage());
mv.setViewName("/error.jsp");
return mv;
}
}
Tips:如果异常被Controller中的某个ExceptionHandler方法匹配了,那么不会进入自定义的异常解析器;
6.2.3 注解方式实现全局异常
package com.dfbz.exception;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class AnnoMyExceptionHandler {
@ExceptionHandler(value = ArithmeticException.class)
public String arithmeticExceptionHandler(Model model, Exception e) {
model.addAttribute("message", e.getMessage());
return "forward:/error.jsp";
}
@ExceptionHandler(Exception.class)
public String exceptionHandler(Model model, Exception e) {
model.addAttribute("message", e.getMessage());
return "forward:/error.jsp";
}
}
Tips:
- 1)当同时定义了异常解析器(HandlerExceptionResolver)和@ControllerAdvice时,@ControllerAdvice优先级高;
- 2)如果@ControllerAdvice标注的异常和Controller方法定义的异常冲突,则以Controller中标注有@ExceptionHandler的方法优先;
|