springmvc 容器启动时,会自动初始化三个异常处理器类:
1.ExceptionHandlerExceptionResolver
2.ResponseStatusExceptionResolver 3.DefaultHandlerExceptionResolver且分别设置了相应的order 由上到下依次为0,1,2
这里ExceptionHandlerExceptionResolver 会使用@ExceptionHandler注解的方法来进行异常处理
由此想到一种分开处理restApi 和 页面异常的方法:
1.使用注解的方式定义异常处理类:
@ControllerAdvice@ResponseBody//这里设置返回数据到响应体public class RestExceptionHandler{ private static final Logger log = LoggerFactory.getLogger(RestExceptionHandler.class); @ExceptionHandler(Exception.class) public CommonResult handler(HandlerMethod handlerMethod, Exception e){//这里引入handlerMethod Method m = handlerMethod.getMethod(); Class clazz = handlerMethod.getBeanType(); //判断访问的url是否为rest 请求 boolean isRestReq = (m.getAnnotation(ResponseBody.class)!=null||clazz.getAnnotation(ResponseBody.class)!=null ||clazz.getAnnotation(RestController.class)!=null); if(isRestReq){//如果为rest请求,则返回数据 CommonResult cr = new CommonResult(); cr.setMsg(e.getMessage()); cr.setCode(500); return cr; }else{//如果不是rest请求,则抛出异常 throw new RuntimeException("handler"); } }}
这里处理rest api 访问的异常,首先判断rest请求,这里通过判断注解的方式来判断,如果不是rest请求则抛出异常,交由后面的异常处理器处理
2.注入页面异常处理类:
这里处理页面请求
这样可以实现分开处理rest 和页面访问的异常 ,要求spring版本4.2.5及其以上