假设下面的代码是用Quarkus编写的。但也可以和micronaut在一起。
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@APIResponses(
value = {
@APIResponse(
responseCode = "201",
description = "Customer Created"),
@APIResponse(
responseCode = "400",
description = "Customer already exists for customerId")
}
)
public Response post(@Valid Customer customer) {
final Customer saved = customerService.save(customer);
return Response.status(Response.Status.CREATED).entity(saved).build();
}客户定义包括字段pictureUrl。CustomerService负责验证网址是否有效,以及图像是否确实存在。
这意味着服务将处理以下异常: MalformedURLException和IOException。CustomerService捕获这些错误并抛出特定于应用程序的异常,以报告映像不存在或路径不正确: ApplicationException。
如何使用microprofile记录此错误情况?
我的研究表明,我必须实现如下形式的异常映射器:
public class ApplicationExceptionMapper implements ExceptionMapper<NotFoundException> {
@Override
@APIResponse(responseCode = "404", description = "Image not Found",
content = @Content(
schema = @Schema(implementation = Customer.class)
)
)
public Response toResponse(NotFoundException t) {
return Response.status(404, t.getMessage()).build();
}
}一旦我有了这样的映射器,框架就会知道如何将我的异常转换为响应。我的分析正确吗?最佳实践是什么?
发布于 2021-06-17 22:28:38
你或多或少指出了正确的方向,你的问题可以分为两部分,让我分别回答这两个问题:
使用microprofile openapi来记录错误:使用api响应和操作描述是正确的方式,如果您愿意,您可以包括错误的扩展描述和与每个错误相关的特定
处理您已经解释过的场景的一种常见的好策略是,使用一系列自定义异常来扩展WebApplicationException,您可以在其中指定响应代码和消息,或者只使用jax-rs提供的异常。如果您需要使用i18n支持进行进一步的自定义,或者需要为响应实体提供与错误相关的详细信息,那么可以实现ExceptionMapper。
https://stackoverflow.com/questions/67954509
复制相似问题