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

自定义HTTP默认状态码的错误响应实现方案问询

如何覆盖HTTP默认状态码响应(如404、503)

当访问不存在的接口路径(比如把/api/v1/search误写为/api/v1/sear),框架会返回带timestamp、status等字段的默认响应,我们可以通过以下两种方式替换成自定义格式的响应:

方式一:自定义ErrorController全局处理错误路径

通过实现Spring Boot的ErrorController接口,接管默认的错误处理逻辑,返回自定义格式:

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;

@RestController
public class CustomErrorController implements ErrorController {

    @RequestMapping("/error")
    public ResponseEntity<Map<String, String>> handleError(HttpServletRequest request) {
        Map<String, String> response = new HashMap<>();
        HttpStatus status = getStatus(request);

        response.put("code", String.valueOf(status.value()));
        // 根据不同状态码设置自定义提示
        switch (status.value()) {
            case 404:
                response.put("message", "资源未找到,请检查路径拼写");
                break;
            case 503:
                response.put("message", "服务暂时不可用,请稍后重试");
                break;
            default:
                response.put("message", status.getReasonPhrase());
        }

        return new ResponseEntity<>(response, status);
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        try {
            return HttpStatus.valueOf(statusCode);
        } catch (Exception ex) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
    }
}

这个类会处理所有跳转到/error的请求(Spring Boot默认错误路径),从请求中获取状态码,然后返回你需要的{code, message}格式响应。

方式二:用@ControllerAdvice捕获特定异常

针对404、503对应的异常,单独编写处理逻辑,需要配合配置开启异常抛出:

1. 添加全局异常处理器

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.NoHandlerFoundException;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class GlobalExceptionHandler {

    // 处理404异常
    @ExceptionHandler(NoHandlerFoundException.class)
    public ResponseEntity<Map<String, String>> handle404(NoHandlerFoundException ex) {
        Map<String, String> response = new HashMap<>();
        response.put("code", "404");
        response.put("message", "资源未找到,请检查路径拼写");
        return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
    }

    // 处理503异常
    @ExceptionHandler(org.springframework.web.server.ServiceUnavailableException.class)
    public ResponseEntity<Map<String, String>> handle503(org.springframework.web.server.ServiceUnavailableException ex) {
        Map<String, String> response = new HashMap<>();
        response.put("code", "503");
        response.put("message", "服务暂时不可用,请稍后重试");
        return new ResponseEntity<>(response, HttpStatus.SERVICE_UNAVAILABLE);
    }

    // 可扩展其他状态码的异常处理
}

2. 配置文件开启异常抛出

在application.properties中添加以下配置,让框架在找不到接口时抛出NoHandlerFoundException:

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

两种方式按需选择:第一种适合全局统一处理所有错误状态码,第二种更灵活,可以针对特定异常做个性化处理。

内容的提问来源于stack exchange,提问作者Achutha K

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 18:15:23