@ControllerAdvice,是Spring3.2提供的新注解,它是一个Controller增强器,可对controller中被 @RequestMapping注解的方法加一些逻辑处理。最常用的就是异常处理
统一异常处理
需要配合@ExceptionHandler使用。
当将异常抛到controller时,可以对异常进行统一处理,规定返回的json格式或是跳转到一个错误页面
//全局异常捕捉处理
@ControllerAdvice
public class CustomExceptionHandler {@ResponseBody@ExceptionHandler(value = Exception.class)public Map errorHandler(Exception ex) {Map map = new HashMap();map.put("code", 400);//判断异常的类型,返回不一样的返回值if(ex instanceof MissingServletRequestParameterException){map.put("msg","缺少必需参数:"+((MissingServletRequestParameterException) ex).getParameterName());}else if(ex instanceof MyException){map.put("msg","这是自定义异常");}return map;}
}
//自定义异常类
@Data
public class MyException extends RuntimeException {private long code;private String msg;public MyException(Long code, String msg){super(msg);this.code = code;this.msg = msg;}public MyException(String msg){super(msg);this.msg = msg;}
}
@RestController
public class TestController {@RequestMapping("testException")public String testException() throws Exception{throw new MissingServletRequestParameterException("name","String");}@RequestMapping("testMyException")public String testMyException() throws MyException{throw new MyException("i am a myException");}
}
分别访问testException
和testMyException
接口,可得到以下结果
{"msg":"缺少必需参数:name","code":400}
{"msg":"这是自定义异常","code":400}
如果不需要返回json数据,而要渲染某个页面模板返回给浏览器,那么可以这么实现:
@ExceptionHandler(value = MyException.class)
public ModelAndView myErrorHandler(MyException ex) {ModelAndView modelAndView = new ModelAndView();//指定错误页面的模板页modelAndView.setViewName("error");modelAndView.addObject("code", ex.getCode());modelAndView.addObject("msg", ex.getMsg());return modelAndView;
}
这样子很方便吧~