解决spring boot无法捕捉404异常问题

系统做了一个全局异常,对各种异常进行封装,统一返回。
代码如下:

@ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    @ResponseBody
    public ResponseEntity handle404(NoHandlerFoundException e) {

        LOGGER.info("Resource Not found, RequestURL: {}, HttpMethod: {}, Headers: {}", e.getRequestURL(),
                e.getHttpMethod(), e.getHeaders());
        LOGGER.error(e.getMessage(), e);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);

        return new ResponseEntity<>(new ErrorResponse(WebExceptionCode.NOT_FOUND), headers, HttpStatus.NOT_FOUND);
    }

但是在使用过程中,发现404时,根本没办法进入到该异常处理。经查,是spring mvc 在异常时,没有抛出404异常。
处理办法如下:

#出现错误时, 直接抛出异常
spring.mvc.throw-exception-if-no-handler-found=true
#不要为我们工程中的资源文件建立映射
spring.resources.add-mappings=false

经测试,处理正常!

你可能感兴趣的:(解决spring boot无法捕捉404异常问题)