@RestControllerAdvice实现springboot全局异常类不生效问题

本文介绍了如何在Java应用中实现全局异常处理。首先创建了一个自定义的`CustomException`类,然后创建了`GlobalExceptionHandler`来捕获并处理`CustomException`和一般异常。接着,通过配置`InterceptorConfig`和`BusinessExceptionHandler`实现了基于拦截器的异常处理,确保全局异常的统一管理和响应。

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

1、先创建一个自定义CustomException 类

public class CustomException extends RuntimeException
{
    private static final long serialVersionUID = 1L;

    private Integer code;

    private String message;

    public CustomException(String message)
    {
        this.message = message;
    }

    public CustomException(String message, Integer code)
    {
        this.message = message;
        this.code = code;
    }

    public CustomException(String message, Throwable e)
    {
        super(message, e);
        this.message = message;
    }

    @Override
    public String getMessage()
    {
        return message;
    }

    public Integer getCode()
    {
        return code;
    }
}

2、创建全局异常类

/**
 * 全局异常处理器
 *
 * @author zz
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    
    /**
     * 业务异常
     */
    @ExceptionHandler(CustomException.class)
    public Result businessException(CustomException e) {
        if (StringUtils.isNull(e.getCode()))
        {
            return Result.error(e.getMessage());
        }
        return Result.error(e.getCode(), e.getMessage());
    }



    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e)
    {
        log.error(e.getMessage(), e);
        return Result.error(e.getMessage());
    }


    /**
     * 参数校验  validation 验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object validExceptionHandler(MethodArgumentNotValidException e) {
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        String message = objectError.getDefaultMessage();
        return Result.error(message);
    }

}

这样觉得没有问题,但是在使用的时候是不生效的 如图:

  

那只换一种方式

1、先创建 InterceptorConfig

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
        resolvers.add(new BusinessExceptionHandler());
    }
}

2、继承HandlerExceptionResolver 类

/**
 * 实现异常类的处理
 */
@Component
public class BusinessExceptionHandler implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        if(e instanceof CustomException) {
            modelAndView.addObject("msg", ((CustomException) e).getMessage());
            modelAndView.addObject("code", ((CustomException) e).getCode());
        }else  if(e instanceof MethodArgumentNotValidException){
            // 从异常对象中拿到ObjectError对象
            ObjectError objectError = ((MethodArgumentNotValidException)e).getBindingResult().getAllErrors().get(0);
            // 然后提取错误提示信息进行返回
            modelAndView.addObject("msg", objectError.getDefaultMessage());
            modelAndView.addObject("code", HttpStatus.PARAMETER);
        }

        return modelAndView;
    }
}

验证效果:实现全局异常。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值