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

如何在Quarkus中配置不存在路径的JSON格式404响应?

在Quarkus中配置不存在路径返回JSON格式404响应

问题描述

访问不存在的路径(例如http://localhost:8080/some-wrong-path)时,Quarkus默认返回HTML格式的404响应,这不适用于纯API服务场景。需要将其替换为JSON格式响应,且不能使用ExceptionMapper<WebApplicationException>或ContainerResponseFilter(因为路径不存在的情况会在这些实现之前被处理)。

默认HTML响应

<html>
<head>
    <title>Error</title>
</head>
<body>Not Found</body>
</html>

期望JSON响应

{
  "error": "Whatever error",
  "details": "Potentially further details"
}

解决方案:实现NotFoundHandler接口

Quarkus提供了io.quarkus.vertx.web.NotFoundHandler接口,用于处理路由未匹配的情况,该处理逻辑会在JAX-RS异常映射器之前执行,完全符合需求。

1. 创建自定义实现类

编写一个ApplicationScoped的类实现NotFoundHandler,自定义404响应的内容和格式:

import io.quarkus.vertx.web.NotFoundHandler;
import io.vertx.core.http.HttpHeaders;
import io.vertx.ext.web.RoutingContext;
import jakarta.enterprise.context.ApplicationScoped;

@ApplicationScoped
public class JsonNotFoundHandler implements NotFoundHandler {

    @Override
    public void handle(RoutingContext rc) {
        rc.response()
                .setStatusCode(404)
                .putHeader(HttpHeaders.CONTENT_TYPE, "application/json")
                .end("{\"error\": \"Resource not found\", \"details\": \"The requested path does not exist on this server\"}");
    }
}

2. 验证效果

启动应用后访问任意不存在的路径,将收到JSON格式的404响应,示例如下:

{
  "error": "Resource not found",
  "details": "The requested path does not exist on this server"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 10:02:05