Quarkus Resteasy Reactive中如何将Uni<Void>转为404响应?
解决方法
针对你的问题,你可以通过Quarkus的Uni API处理链,把Uni<Void>的结果转换成404响应,下面是几种实用的实现方式:
方式一:抛出标准NotFoundException
利用JAX-RS的异常自动映射机制,当service返回Void时抛出NotFoundException,框架会自动返回404状态码:
@GET @Path("{id}") public Uni<Stuff> getSomeStuff(@PathParam("id") int id) { return someService.fetchStuff(id) .onItem().failWith(() -> new NotFoundException("Stuff ID " + id + " not found")); }
方式二:主动构建失败的Uni实例
直接在Void结果的处理逻辑中,返回一个包含失败的Uni,同样触发404:
@GET @Path("{id}") public Uni<Stuff> getSomeStuff(@PathParam("id") int id) { return someService.fetchStuff(id) .onItem().transformToUni(voidVal -> Uni.createFrom().failure(new NotFoundException("Requested Stuff doesn't exist")) ); }
方式三:手动构建Response响应
如果不想依赖异常映射,可以把方法返回类型改成Uni<Response>,手动组装404响应内容:
@GET @Path("{id}") public Uni<Response> getSomeStuff(@PathParam("id") int id) { return someService.fetchStuff(id) .onItem().transform(voidVal -> Response.status(Response.Status.NOT_FOUND) .entity("No Stuff found with ID: " + id) .build() ); }
注意点
NotFoundException是JAX-RS的标准异常,无需额外配置就能被框架识别并映射为404状态码。- 三种方式都能把原本返回204的逻辑替换成404,根据你的代码风格选择即可。
内容的提问来源于stack exchange,提问作者Marc
相关产品推荐
相关产品推荐

