spring boot 404 自定义拦截问题

博客提到在 Spring MVC 中,当配置出现异常时,可直接抛出并交给自定义的异常监听处理,给出了配置代码 spring.mvc.throw - exception - if - no - handler - found=true。

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

#配置出现异常 直接抛出 交给自定义的异常监听处理
spring.mvc.throw-exception-if-no-handler-found=true

/**
 * 异常监听类
 * Created by liqun on 2018/4/19.
 */
@ControllerAdvice
public class ExceptionHandle {
    private final static Logger LOGGER = LoggerFactory.getLogger(ExceptionHandle.class);


    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result exceptionGet(Exception e){
       
        //请求方式不正确
        if(e instanceof HttpRequestMethodNotSupportedException){
            return ResultUtil.error(ExceptionEnum.HTTP_METHOD);
        }
        //404
        if(e instanceof NoHandlerFoundException){//404
            return ResultUtil.error(ExceptionEnum.NO_METHOD_ERROR);
        }
        /**
         * 如果抛出的自定义redis 异常
         */
        if(e instanceof RedisException){
            DescribeException myException = (DescribeException) e;
            return ResultUtil.error(myException.getCode(),myException.getMessage());
        }
        /**
         * 自定义错误异常
         */
        if(e instanceof CustomException){
            return ResultUtil.error(((CustomException)e).getCode(),((CustomException)e).getMessage());
        }
        /**
         * 权限验证
         */
        if(e instanceof AuthenticationException){
            return ResultUtil.error(ExceptionEnum.SHIRO_LOGIN_ERROR);
        }
        if(e instanceof UnauthorizedException ){
            return ResultUtil.error(ExceptionEnum.NO_AUTHORITY);
        }

 
        if(e instanceof TokenException){
            return ResultUtil.error(ExceptionEnum.TOKENT_ERROR);
        }
        LOGGER.error("未知异常",e);
        return ResultUtil.error(ExceptionEnum.UNKNOW_ERROR);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值