SpringBoot @ControllerAdvice 拦截异常并统一处理
在spring3.2中,新增了@ControllerAdvice注解,可以用于定义@ExceptionHandler、@InitBinder、@ModelAttribute,并应用到所有@RequestMapping中。参考:@ControllerAdvice文档
一、介绍
创建MyControllerAdvice,并添加@ControllerAdvice注解。
packagecom.sam.demo.controller; importorg.springframework.ui.Model; importorg.springframework.web.bind.WebDataBinder; importorg.springframework.web.bind.annotation.*; importjava.util.HashMap; importjava.util.Map; /** *controller增强器 *@authorsam *@since2017/7/17 */ @ControllerAdvice publicclassMyControllerAdvice{ /** *应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器 *@parambinder */ @InitBinder publicvoidinitBinder(WebDataBinderbinder){} /** *把值绑定到Model中,使全局@RequestMapping可以获取到该值 *@parammodel */ @ModelAttribute publicvoidaddAttributes(Modelmodel){ model.addAttribute("author","MagicalSam"); } /** *全局异常捕捉处理 *@paramex *@return */ @ResponseBody @ExceptionHandler(value=Exception.class) publicMaperrorHandler(Exceptionex){ Mapmap=newHashMap(); map.put("code",100); map.put("msg",ex.getMessage()); returnmap; } }
启动应用后,被@ExceptionHandler、@InitBinder、@ModelAttribute注解的方法,都会作用在被@RequestMapping注解的方法上。
@ModelAttribute:在Model上设置的值,对于所有被@RequestMapping注解的方法中,都可以通过ModelMap获取,如下:
@RequestMapping("/home") publicStringhome(ModelMapmodelMap){ System.out.println(modelMap.get("author")); } //或者通过@ModelAttribute获取 @RequestMapping("/home") publicStringhome(@ModelAttribute("author")Stringauthor){ System.out.println(author); }
@ExceptionHandler拦截了异常,我们可以通过该注解实现自定义异常处理。其中,@ExceptionHandler配置的value指定需要拦截的异常类型,上面拦截了Exception.class这种异常。
二、自定义异常处理(全局异常处理)
springboot默认情况下会映射到/error进行异常处理,但是提示并不十分友好,下面自定义异常处理,提供友好展示。
1、编写自定义异常类:
packagecom.sam.demo.custom; /** *@authorsam *@since2017/7/17 */ publicclassMyExceptionextendsRuntimeException{ publicMyException(Stringcode,Stringmsg){ this.code=code; this.msg=msg; } privateStringcode; privateStringmsg; //getter&setter }
注:spring对于RuntimeException异常才会进行事务回滚。
2、编写全局异常处理类
创建MyControllerAdvice.java,如下:
packagecom.sam.demo.controller; importorg.springframework.ui.Model; importorg.springframework.web.bind.WebDataBinder; importorg.springframework.web.bind.annotation.*; importjava.util.HashMap; importjava.util.Map; /** *controller增强器 * *@authorsam *@since2017/7/17 */ @ControllerAdvice publicclassMyControllerAdvice{ /** *全局异常捕捉处理 *@paramex *@return */ @ResponseBody @ExceptionHandler(value=Exception.class) publicMaperrorHandler(Exceptionex){ Mapmap=newHashMap(); map.put("code",100); map.put("msg",ex.getMessage()); returnmap; } /** *拦截捕捉自定义异常MyException.class *@paramex *@return */ @ResponseBody @ExceptionHandler(value=MyException.class) publicMapmyErrorHandler(MyExceptionex){ Mapmap=newHashMap(); map.put("code",ex.getCode()); map.put("msg",ex.getMsg()); returnmap; } }
3、controller中抛出异常进行测试。
@RequestMapping("/home") publicStringhome()throwsException{ //thrownewException("Sam错误"); thrownewMyException("101","Sam错误"); }
启动应用,访问:http://localhost:8080/home,正常显示以下json内容,证明自定义异常已经成功被拦截。
{"msg":"Sam错误","code":"101"}
*如果不需要返回json数据,而要渲染某个页面模板返回给浏览器,那么MyControllerAdvice中可以这么实现:
@ExceptionHandler(value=MyException.class) publicModelAndViewmyErrorHandler(MyExceptionex){ ModelAndViewmodelAndView=newModelAndView(); modelAndView.setViewName("error"); modelAndView.addObject("code",ex.getCode()); modelAndView.addObject("msg",ex.getMsg()); returnmodelAndView; }
在templates目录下,添加error.ftl(这里使用freemarker)进行渲染:
错误页面 $[code]
${msg}