优秀的编程知识分享平台

网站首页 > 技术文章 正文

@ControllerAdvice注解(全局异常捕获)

nanyue 2024-09-03 16:18:40 技术文章 14 ℃



背景

@ControllerAdvice 注解 通常用于定义@ExceptionHandler, @InitBinder和@ModelAttribute 适用于所有@RequestMapping方法的方法。

@ExceptionHandler异常处理器

作用:可以拦截程序抛出来的指定异常。使用场景:主要使用与项目统一异常处理,对于rest风格的返回统一异常格式。

/**
       * 指定拦截异常的类型
       *
       * @param e
       * @return json格式类型
       */
@ExceptionHandler({Exception.class}) //指定拦截异常的类型
    @ResponseBody
    public Object customExceptionHandler(Exception e) {
        //打印异常日志
        e.printStackTrace();
        //非空验证异常
        if(e instanceof BindException){
            BindException bindException = (BindException) e;
            String msg =  bindException.getBindingResult().getFieldError().getDefaultMessage();
            return msg;
        }
        if(e instanceof GlobalException){
            GlobalException globalException = (GlobalException) e;
            return globalException.getErrMsg();
        }
        return "系统异常";
    }

@InitBinder

作用:
应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器
使用场景:
1.可用于绑定作用于全局的请求参数验证器。
2.日期格式把请求中的日期字符串转换成Date类型。

/**
       * 应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器
       *
       * @param binder
       

自定义参数验证器使用传送门:SpringBoot自定义参数验证器

@ModelAttribute

作用:把值绑定到Model中,使全局@RequestMapping可以获取到该值

使用场景:大家发挥自己那聪明的小脑袋吧,本人也没想到哪里实战使用!

/**
     * 把值绑定到Model中,使全局@RequestMapping可以获取到该值 
     *
     * @param model
     */
    @ModelAttribute
    public void addAttribute(Model model) {
        model.addAttribute("msg", "hello");
    }

获取参数:

 @GetMapping("test")
       @ResponseBody
       public Object test(@ModelAttribute("msg") String msg){
             return msg;
       }

完整的代码

package com.wzq.config.exception;
import org.springframework.ui.Model;
import org.springframework.validation.BindException
;import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;


/**
 * @description: 全局异常处理类
 * @author: Wzq
 * @create: 2019-12-26 11:01
 */
@RestControllerAdvice
public class GlobalExceptionAdvice {

    
    /**
     * 指定拦截异常的类型
     *
     * @param e
     * @return json格式类型
     */
    @ExceptionHandler({Exception.class}) //指定拦截异常的类型
    @ResponseBody
    public Object customExceptionHandler(Exception e) {
        //打印异常日志
        e.printStackTrace();
        //非空验证异常
        if(e instanceof BindException){
            BindException bindException = (BindException) e;
            String msg =  bindException.getBindingResult().getFieldError().getDefaultMessage();
            return msg;
        }
        if(e instanceof GlobalException){
            GlobalException globalException = (GlobalException) e;
            return globalException.getErrMsg();
        }
        return "系统异常";
    }


    /**
     * 应用到所有@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("msg", "hello");
    }


}

@RestControllerAdvice 和 @ControllerAdvice区别在于@RestControllerAdvice不需要加@ResponseBody


转载自GoslingWu,未经许可,严禁抄袭

更多相关内容,Java&python,软件开发等学习资料,电子书及视频还有高级讲师免费课程,

需要的可以私聊小编发送【学习】二字

最近发表
标签列表