Spring中@ControllerAdvice注解配合@ExceptionHandler实现统一异常处理

本文详细介绍了Spring 3.2中新增的@ControllerAdvice注解的使用方法,包括如何利用@ExceptionHandler、@InitBinder和@ModelAttribute进行全局异常处理、数据绑定和模型属性初始化,并提供了具体示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在spring 3.2中,新增了@ControllerAdvice注解,可以用于定义@ExceptionHandler、@InitBinder、@ModelAttribute并应用到所有@RequestMapping中。参考:@ControllerAdvice 文档

 

从注解的名很清楚的知道,该注解是一个面向切面编程的用于controller方法增强的注解,@ControllerAdvice的实现:

@Target(ElementType.TYPE)  
@Retention(RetentionPolicy.RUNTIME)  
@Documented  
@Component  
public @interface ControllerAdvice {  
} 

  • @ControllerAdvice详解

先看以下代码:

    @ControllerAdvice  
    public class GlobalExceptionHandler {  
      
        /**
         * 应用到所有@RequestMapping注解方法,在其执行之前把返回值放入Model
         */
        @ModelAttribute  
        public void newUser() {  
        }  
      
        /**
         * 应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器
         */
        @InitBinder  
        public void initBinder(WebDataBinder binder) {    
        }  
      
        /**
         * 应用到所有@RequestMapping注解的方法,在其抛出BusinessException异常时执行
         */
        @ExceptionHandler(BusinessException.class)  
        @ResponseBody
        public ApiResult<String> businessExceptionHandler(HttpServletRequest req, BusinessException e) throws Exception {
            ApiResult<String> apiResult = new ApiResult<>();
            apiResult.fail(e.getMessage());
            return apiResult;
        }
    }

使用@ExceptionHandler、@InitBinder、@ModelAttribute注解的方法,都会作用于使用@RequestMapping注解的方法上。

  • 自定义统一异常处理

1.编写自定义异常类:

public class BusinessException extends RuntimeException {

    public BusinessException() {
         super();
    }
    
    public BusinessException(String message) {
        super(message);
    }
}

2.编写全局异常处理类:

@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Log logger = LogFactory.getLog(GlobalExceptionHandler.class);

    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public ApiResult<String> businessExceptionHandler(HttpServletRequest req, BusinessException e) throws Exception {
        ApiResult<String> apiResult = new ApiResult<>();
        apiResult.fail(e.getMessage());
        return apiResult;
    }
    
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ApiResult<String> exceptionHandler(HttpServletRequest req, Exception e) throws Exception {
        ApiResult<String> apiResult = new ApiResult<>();
         logger.error(e.getMessage(), e);
         apiResult.dataError();
        return apiResult;
    }

}

通过以上代码编写之后,只要是使用@RequestMapping注解的方法,抛出BusinessException和Exception都会自动统一调用businessExceptionHandler和exceptionHandler方法,进行异常处理。

补充:如果统一异常处理都需要返回json,那么可以使用@RestControllerAdvice注解来代替@ControllerAdvice,这样就可不需要添加@ResponseBody。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乐只乐之

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值