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

本地正常的Spring JSON错误响应部署到服务器后自动转HTML的解决方法

解决部署到Tomcat后错误响应从JSON变为HTML的问题

这个问题我之前踩过坑,本质是Tomcat在捕获到服务器端错误时,默认触发了它自带的HTML错误页面,覆盖了我们应用生成的JSON响应。下面几个方案可以针对性解决:

1. 检查前端请求的Accept头

先确认前端发送请求时,Accept请求头是否设置为application/json。Tomcat会根据内容协商机制返回响应类型,如果请求头里包含text/html或者没指定Accept,Tomcat就会优先返回它的默认HTML错误页。本地运行时可能前端请求默认带了正确的Accept头,服务器环境下却没配置,导致了差异。

2. Spring Boot项目:强制返回JSON错误响应

如果你的项目是Spring Boot,可以通过配置覆盖Tomcat的默认行为:

  • 方式一:关闭白标错误页+配置异常处理
    在application.properties中添加:
server.error.whitelabel.enabled=false
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false
  • 方式二:自定义错误控制器
    创建配置类,强制所有错误返回JSON格式:
@Configuration
public class JsonErrorConfiguration {
    @Bean
    public ErrorController customErrorController(ErrorAttributes errorAttributes) {
        return new BasicErrorController(errorAttributes) {
            @Override
            public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
                Map<String, Object> errorDetails = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
                HttpStatus status = getStatus(request);
                // 可以在这里自定义返回的JSON字段,和你本地的格式对齐
                return new ResponseEntity<>(errorDetails, status);
            }
        };
    }
}

3. 非Spring项目:配置Tomcat错误页面映射

如果是普通Java Web项目,可以直接在web.xml中配置错误页的映射,指定返回JSON:

<error-page>
    <error-code>500</error-code>
    <location>/json-error-handler</location>
</error-page>

然后编写一个Servlet或者JSP处理/json-error-handler路径,输出JSON格式的错误响应,示例Servlet代码:

@WebServlet("/json-error-handler")
public class JsonErrorHandlerServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json");
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        String message = (String) request.getAttribute("javax.servlet.error.message");
        
        String jsonResponse = String.format("{\"timestamp\":\"%s\",\"status\":%d,\"error\":\"Internal Server Error\",\"message\":\"%s\",\"path\":\"%s\"}",
                LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME),
                statusCode,
                message != null ? message : "Unknown error",
                request.getRequestURI());
        
        response.getWriter().write(jsonResponse);
    }
}

4. 检查全局异常处理器是否生效

本地运行时正常的全局异常处理器(比如@ControllerAdvice+@ExceptionHandler),部署到服务器后可能因为类扫描范围、配置优先级问题失效。检查你的异常处理类是否被Spring正确扫描,有没有被其他配置覆盖。

内容的提问来源于stack exchange,提问作者Munal Dhakal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:11:13