Java自学者论坛

 找回密码
 立即注册

手机号码,快捷登录

恭喜Java自学者论坛(https://www.javazxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,会员资料板块,购买链接:点击进入购买VIP会员

JAVA高级面试进阶训练营视频教程

Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程Go语言视频零基础入门到精通Java架构师3期(课件+源码)
Java开发全终端实战租房项目视频教程SpringBoot2.X入门到高级使用教程大数据培训第六期全套视频教程深度学习(CNN RNN GAN)算法原理Java亿级流量电商系统视频教程
互联网架构师视频教程年薪50万Spark2.0从入门到精通年薪50万!人工智能学习路线教程年薪50万大数据入门到精通学习路线年薪50万机器学习入门到精通教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程MySQL入门到精通教程
查看: 398|回复: 0

精通Spring Boot---使用@ControllerAdvice处理异常

[复制链接]
  • TA的每日心情
    奋斗
    2024-11-24 15:47
  • 签到天数: 804 天

    [LV.10]以坛为家III

    2053

    主题

    2111

    帖子

    72万

    积分

    管理员

    Rank: 9Rank: 9Rank: 9

    积分
    726782
    发表于 2021-7-5 12:15:28 | 显示全部楼层 |阅读模式

    在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。

    哎...今天够累的,签到来了1...
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|小黑屋|Java自学者论坛 ( 声明:本站文章及资料整理自互联网,用于Java自学者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2025-2-1 09:54 , Processed in 0.058219 second(s), 29 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表