Spring Boot访问不存在的@RestController端点时抛出的异常类是什么?
处理Spring Boot中不存在的REST端点异常问题
当请求@RestController中不存在的端点时,Spring Boot对应的异常类是org.springframework.web.servlet.NoHandlerFoundException。
但默认情况下你捕获不到这个异常,因为Spring Boot的默认配置里,spring.mvc.throw-exception-if-no-handler-found参数值为false,此时系统不会抛出该异常,而是直接返回404响应体。要让这个异常能被@ControllerAdvice的@ExceptionHandler捕获,需要先修改配置:
在
application.properties中添加:spring.mvc.throw-exception-if-no-handler-found=true spring.web.resources.add-mappings=false(第二个配置是为了避免静态资源请求触发同样的异常,如果你不需要处理静态资源的404,可以根据情况调整)
或者在
application.yml中添加:spring: mvc: throw-exception-if-no-handler-found: true web: resources: add-mappings: false
配置完成后,就可以在@ControllerAdvice中添加对应的异常处理方法:
@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(NoHandlerFoundException.class) public ResponseEntity<Map<String, Object>> handleNoHandlerFoundException(NoHandlerFoundException ex) { Map<String, Object> response = new HashMap<>(); response.put("code", 404); response.put("message", "请求的接口不存在:" + ex.getRequestURL()); return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); } }
这样就能自定义不存在端点时的响应内容了。
内容的提问来源于stack exchange,提问作者Daniel Pinheiro
相关产品推荐
相关产品推荐

