精通Spring Boot —— 第十五篇:使用@ControllerAdvice处理异常
在Spring 3.2中,新增了@ControllerAdvice、@RestControllerAdvice 注解,可以用于定义@ExceptionHandler、@InitBinder、@ModelAttribute,并应用到所有@RequestMapping、@PostMapping, @GetMapping注解中。
接下来我将通过代码展示如何使用这些注解,以及处理异常。
1.注解的介绍
先定义一个ControllerAdvice。代码如下
/** * @author Lensen * @desc * @since 2018/10/5 11:01 */ @ControllerAdvice public class MyExceptionHandler { /** * 应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器 * @param binder */ @InitBinder public void initWebBinder(WebDataBinder binder){ //对日期的统一处理 binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd")); //添加对数据的校验 //binder.setValidator(); } /** * 把值绑定到Model中,使全局@RequestMapping可以获取到该值 * @param model */ @ModelAttribute public void addAttribute(Model model) { model.addAttribute("attribute", "The Attribute"); } /** * 捕获CustomException * @param e * @return json格式类型 */ @ResponseBody @ExceptionHandler({CustomException.class}) //指定拦截异常的类型 @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) //自定义浏览器返回状态码 public Map<String, Object> customExceptionHandler(CustomException e) { Map<String, Object> map = new HashMap<>(); map.put("code", e.getCode()); map.put("msg", e.getMsg()); return map; } /** * 捕获CustomException * @param e * @return 视图 */ // @ExceptionHandler({CustomException.class}) // public ModelAndView customModelAndViewExceptionHandler(CustomException e) { // Map<String, Object> map = new HashMap<>(); // map.put("code", e.getCode()); // map.put("msg", e.getMsg()); // ModelAndView modelAndView = new ModelAndView(); // modelAndView.setViewName("error"); // modelAndView.addObject(map); // return modelAndView; // } }
需要注意的是使用@ExceptionHandler注解传入的参数可以一个数组,且使用该注解时,传入的参数不能相同,也就是不能使用两个@ExceptionHandler去处理同一个异常。如果传入参数相同,则初始化ExceptionHandler时会失败。
对于@ControllerAdvice注解,我们来看看源码的定义:
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface ControllerAdvice { @AliasFor("basePackages") String[] value() default {}; @AliasFor("value") String[] basePackages() default {}; Class<?>[] basePackageClasses() default {}; Class<?>[] assignableTypes() default {}; Class<? extends Annotation>[] annotations() default {}; }
我们可以传递basePackage,声明的类(是一个数组)指定的Annotation参数,具体参考:spring framework doc
2.异常的处理
编写自定义异常类
package com.developlee.errorhandle.exception; /** * @author Lensen * @desc 自定义异常类 * @since 2018/10/5 11:04 */ public class CustomException extends RuntimeException { private long code; private String msg; public CustomException(Long code, String msg){ this.code = code; this.msg = msg; } public long getCode() { return code; } public void setCode(long code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
Spring 对于 RuntimeException类的异常才会进行事务回滚,所以我们一般自定义异常都继承该异常类。
编写全局异常处理类
/** * @author Lensen * @desc * @since 2018/10/5 11:01 */ @ControllerAdvice("com.developlee.errorhandle") public class MyExceptionHandler { /** * 应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器 * @param binder */ @InitBinder public void initWebBinder(WebDataBinder binder){ } /** * 把值绑定到Model中,使全局@RequestMapping可以获取到该值 * @param model */ @ModelAttribute public void addAttribute(Model model) { model.addAttribute("attribute", "The Attribute"); } /** * 捕获CustomException * @param e * @return json格式类型 */ @ResponseBody @ExceptionHandler({CustomException.class}) //指定拦截异常的类型 @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) //自定义浏览器返回状态码 public Map<String, Object> customExceptionHandler(CustomException e) { Map<String, Object> map = new HashMap<>(); map.put("code", e.getCode()); map.put("msg", e.getMsg()); return map; } /** * 捕获CustomException * @param e * @return 视图 */ // @ExceptionHandler({CustomException.class}) // public ModelAndView customModelAndViewExceptionHandler(CustomException e) { // Map<String, Object> map = new HashMap<>(); // map.put("code", e.getCode()); // map.put("msg", e.getMsg()); // ModelAndView modelAndView = new ModelAndView(); // modelAndView.setViewName("error"); // modelAndView.addObject(map); // return modelAndView; // } }
测试
在controller中抛出自定义异常
/** * @author Lensen * @desc * @since 2018/10/5 11:00 */ @Controller public class DemoController { /** * 关于@ModelAttribute, * 可以使用ModelMap以及@ModelAttribute()来获取参数值。 */ @GetMapping("/one") public String testError(ModelMap modelMap ) { throw new CustomException(500L, "系统发生500异常!" + modelMap.get("attribute")); } @GetMapping("/two") public String testTwo(@ModelAttribute("attribute") String attribute) { throw new CustomException(500L, "系统发生500异常!" + attribute); } }
启动应用,范围localhost:8080/one.返回报文为:
{"msg":"系统发生500异常!The Attribute","code":500}
可见我们的@InitBinder和@ModelAttribute注解生效。且自定义异常被成功拦截。如果全部异常处理都返回json,那么可以使用 @RestControllerAdvice 代替 @ControllerAdvice ,这样在方法上就可以不需要添加 @ResponseBody。@RestControllerAdvice在注解上已经添加了@ResponseBody。
最后,以上示例代码可在我的github.com中找到。
我的个人公众号:developlee的潇洒人生。
关注了也不一定更新,更新就不得了了。

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
- 上一篇
使用R语言分析微信好友
上篇使用python分析微信好友 - 简书https://www.jianshu.com/p/c7f1b400d20a python爬虫: 数据保存后用R语言作图分析 省份分布 城市分布 微信签名生存词云
- 下一篇
PostgreSQL jdbc 错误代码映射(SQLSTATE)
标签 PostgreSQL , SQLSTATE , 错误代码 , org.postgresql.util.PSQLState 背景 Does such a class enumerating the PostgreSQL error codes already exist? Yes, it does:org.postgresql.util.PSQLState However, there are 238 error codes listed on the page you referenced, andorg.postgresql.util.PSQLStateonly enumerates 41 values. Of those 41 values, only 33 are from that list of PostgreSQL
相关文章
文章评论
共有0条评论来说两句吧...
文章二维码
点击排行
推荐阅读
最新文章
- 设置Eclipse缩进为4个空格,增强代码规范
- Docker快速安装Oracle11G,搭建oracle11g学习环境
- SpringBoot2整合MyBatis,连接MySql数据库做增删改查操作
- CentOS7编译安装Gcc9.2.0,解决mysql等软件编译问题
- CentOS6,CentOS7官方镜像安装Oracle11G
- Docker安装Oracle12C,快速搭建Oracle学习环境
- Docker使用Oracle官方镜像安装(12C,18C,19C)
- SpringBoot2编写第一个Controller,响应你的http请求并返回结果
- SpringBoot2全家桶,快速入门学习开发网站教程
- Jdk安装(Linux,MacOS,Windows),包含三大操作系统的最全安装