首页 > 解决方案 > 在 Quarkus Microprofile 中验证 REST 参数

问题描述

以下代码是 Quarkus Microprofile API 应用程序中控制器的一部分。

    @GET
    @Path("/limit/{limit}/offset/{offset}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response paginatedAccounts(
            @Parameter(
                description = "Number of records to be returned.",
                required = true,
                schema = @Schema(type = SchemaType.INTEGER))
            @PathParam("limit") int limit,
            @Parameter(
                 description = "The starting number of record, zero based.",
                 required = true,
                 schema = @Schema(type = SchemaType.INTEGER))
             @PathParam("offset") int offset)
    {
        return Response
                .ok(this.accountService.getPaginatedAccounts(limit, offset))
                .build();
    }

它返回一个分页的帐户列表。

当用户调用 API 时为“limit”或“offset”提供了错误的类型,即:

http://[url]/[entity]/limit/zzz/offset/0

她收到“404 - 未找到”

如何验证参数“limit”和“offset”,以便当用户提供错误类型(int 的字符串)时,她会收到:

“400 - 错误请求”

应该是这样吗?

标签: apirestquarkusmicroprofile

解决方案


这是设计使然(根据 JAX-RS 规范)。

https://docs.oracle.com/cd/E19798-01/821-1841/6nmq2cp1v/index.html明确提到它:

如果 URI 路径模板变量无法转换为指定类型,则 JAX-RS 运行时会向客户端返回 HTTP 400(“错误请求”)错误。如果无法将 @PathParam 注释转换为指定类型,则 JAX-RS 运行时会向客户端返回 HTTP 404(“未找到”)错误


推荐阅读