解决springboot配置@ControllerAdvice不能捕获Exception问题

在学习自定义异常处理时,为了快捷测试,使用@ExceptionHandler直接捕获了Exception.class,而也没有定义异常,而是直接访问不存在的页面,导致抛出的异常为NoHandlerFoundException

@ControllerAdvice
public class MyExceptionHandler {

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Map<String, Object> handleException(Exception e){
        System.out.println(1);
        Map<String,Object> map = new HashMap<>();
        map.put("message",e.getMessage());
        map.put("ext", "错误");
        return map;
    }
}

但是根据DispatcherServlet源码,只有当this.throwExceptionIfNoHandlerFound为true时才会把异常抛出来,而默认为false,所以在捕获这个异常的时候,需要在配置文件中修改这个属性。

    private boolean throwExceptionIfNoHandlerFound = false;
  protected void noHandlerFound(HttpServletRequest request, HttpServletResponse response) throws Exception {
        if (pageNotFoundLogger.isWarnEnabled()) {
            pageNotFoundLogger.warn("No mapping for " + request.getMethod() + " " + getRequestUri(request));
        }

        if (this.throwExceptionIfNoHandlerFound) {
            throw new NoHandlerFoundException(request.getMethod(), getRequestUri(request), (new ServletServerHttpRequest(request)).getHeaders());
        } else {
            response.sendError(404);
        }
    }

此外,还需要关闭静态资源映射,因为出错后会按error/404,/error等路径去寻找错误页面,找不到就会按照默认建立错误页面。修改后:

spring.mvc.throw-exception-if-no-handler-found=true
spring.web.resources.add-mappings=false
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值