spring boot 捕获路由匹配异常的核心做法是注册一个类型为 handlerexceptionresolver 的 bean,并在其中拦截 nohandlerfoundexception。默认情况下 spring mvc 会忽略未找到的请求并返回 404,通过设置 spring.mvc.throw-exception-if-no-handler-found=true 开启异常抛出,再配合 @restcontrolleradvice 或自定义解析器即可统一处理。

如何配置全局异常处理器来捕获 NoHandlerFoundException
要捕获路由匹配异常,必须先在配置文件中开启 throw-exception-if-no-handler-found 属性,否则 Spring 会直接返回静态 404 页面而不触发任何异常处理逻辑。接着在配置类中关闭资源默认处理 addResourceHandlers,最后定义一个实现 HandlerExceptionResolver 接口的 Bean 或使用 @ExceptionHandler 注解的方法来处理 NoHandlerFoundException。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class ExceptionConfig {
@Bean
public HandlerExceptionResolver noHandlerFoundResolver() {
return (request, response, handler, ex) -> {
if (ex instanceof NoHandlerFoundException) {
response.setStatus(HttpStatus.NOT_FOUND.value());
response.setContentType("application/json;charset=UTF-8");
Map<string object> body = new HashMap();
body.put("error", "Not Found");
body.put("message", "The requested resource is not available");
response.getWriter().write(new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(body));
return new ResponseEntity(body, HttpStatus.NOT_FOUND);
}
return null;
};
}
}</string>
上述代码定义了一个 noHandlerFoundResolver Bean。当请求无法匹配任何控制器时,Spring 会抛出 NoHandlerFoundException。该解析器检查异常类型,如果是则设置响应状态为 404,并写入 JSON 格式的响应体。注意这里需要手动处理 JSON 序列化,或者可以使用更简洁的 @RestControllerAdvice 方式。在实际项目中,推荐使用 @RestControllerAdvice 结合 @ExceptionHandler(NoHandlerFoundException.class) 来实现,这样代码更清晰且自动处理 JSON 序列化。
使用 RestControllerAdvice 简化异常处理流程
相比实现 HandlerExceptionResolver 接口,使用 @RestControllerAdvice 是更现代和推荐的做法。它允许你集中管理所有控制器的异常,并通过 @ExceptionHandler 指定处理特定异常的方法。这种方式代码更少,且与 Spring MVC 的响应机制集成得更好,自动将返回值序列化为 JSON。

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(NoHandlerFoundException.class)
public ResponseEntity<map object>> handleNoHandlerFound(NoHandlerFoundException ex) {
Map<string object> body = new HashMap();
body.put("error", "Not Found");
body.put("message", "The requested resource is not available");
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(body);
}
}</string></map>
这个 GlobalExceptionHandler 类使用了 @RestControllerAdvice 注解,使其成为全局异常处理器。方法 handleNoHandlerFound 使用 @ExceptionHandler(NoHandlerFoundException.class) 来专门处理路由未匹配的异常。当发生 NoHandlerFoundException 时,该方法会被调用,返回一个包含错误信息的 ResponseEntity。这种方法比之前的 HandlerExceptionResolver 实现更简洁,且不需要手动处理 JSON 序列化,因为 Spring 会自动完成这一过程。确保在 application.yml 或 application.properties 中正确配置了 spring.mvc.throw-exception-if-no-handler-found=true 和 spring.web.resources.add-mappings=false(如果需要完全禁用静态资源映射)。
当请求路径包含特殊字符时如何处理
如果请求路径中包含 URL 编码的特殊字符或非法字符,可能会导致 NoHandlerFoundException 或其他解析异常。在这种情况下,除了处理 NoHandlerFoundException 外,还应考虑处理 ServletException 或 IllegalArgumentException 等可能由 URL 解析引起的异常。可以通过在 GlobalExceptionHandler 中添加额外的 @ExceptionHandler 方法来处理这些情况,确保应用程序对各类异常都有适当的响应。











