Spring Boot 无法捕捉 404 异常问题

此文章发布于 61 个月前,部分信息可能已经过时,请自行斟酌确认。

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

@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(value = HttpStatus.NOT_FOUND)
@ResponseBody
public ResponseEntity<ErrorResponse> 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

经测试,处理正常!

最后修改:2019 年 04 月 15 日 10 : 36 PM
如果觉得我的文章对你有用,请随意赞赏

发表评论