You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Spring Boot默认404不存在URL的自定义异常消息?

自定义REST端点404错误响应不生效问题

我尝试为所有不支持的REST端点修改默认错误消息和状态码,具体实现如下:

自定义错误响应类

public class ApiErrorResponse {

    private int code;
    private String message;

    public ApiErrorResponse(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public int getCode() {
        return code;
    }
}

自定义异常处理逻辑

@ControllerAdvice
public class ApiExceptionHandler {

    @ExceptionHandler({NoHandlerFoundException.class})
    public ResponseEntity<ApiErrorResponse> handleNoHandlerFoundException(
            NoHandlerFoundException ex, HttpServletRequest httpServletRequest) {
        ApiErrorResponse apiErrorResponse = new ApiErrorResponse(404, "Resource not found");
        return ResponseEntity.status(HttpStatus.NOT_FOUND).contentType(MediaType.APPLICATION_JSON).body(apiErrorResponse);
    }
}

使用curl命令 curl --location 'localhost:8080/some/invalid/url' 测试后,仍返回默认404状态码和错误消息,而非自定义内容,请问我遗漏了什么?


解决方案

你遗漏了Spring Boot的关键配置,因为默认情况下Spring MVC不会抛出NoHandlerFoundException,需要手动开启相关设置:

1. 添加配置文件参数

根据你的配置文件类型,添加以下配置:

若使用application.properties:

# 让Spring MVC在找不到请求处理器时抛出异常
spring.mvc.throw-exception-if-no-handler-found=true
# 关闭静态资源自动映射,避免静态资源处理器拦截无效请求
spring.web.resources.add-mappings=false

若使用application.yml:

spring:
  mvc:
    throw-exception-if-no-handler-found: true
  web:
    resources:
      add-mappings: false

2. 配置说明

  • spring.mvc.throw-exception-if-no-handler-found=true:强制Spring MVC在没有匹配的请求映射时抛出NoHandlerFoundException,这样你的异常处理器才能捕获到该异常并返回自定义响应。
  • spring.web.resources.add-mappings=false:关闭Spring Boot默认的静态资源映射(比如/static、/public等目录下的资源),否则无效URL可能会被静态资源处理器拦截,无法触发NoHandlerFoundException。

3. 额外检查

确保你的ApiErrorResponse类能够被正确序列化为JSON,你的代码中已经手动实现了getter方法,这已经满足Jackson序列化的要求,无需额外配置。

内容的提问来源于stack exchange,提问作者velmurugan A

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 13:08:29