【问题标题】:How to document internal error with microprofile如何使用微配置文件记录内部错误
【发布时间】:2021-08-29 10:20:04
【问题描述】:

假设使用 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();
    }

客户定义包括一个字段图片Url。 CustomerService 负责验证该 URL 是一个有效的 URL 并且该图像确实存在。

这意味着服务将处理以下异常: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();
    }

}

一旦我有了这样的映射器,框架就会知道如何将我的异常转换为响应。我的分析正确吗?最佳做法是什么?

【问题讨论】:

    标签: quarkus micronaut microprofile eclipse-microprofile-config


    【解决方案1】:

    您或多或少指向了正确的方向,您的问题可以分为两部分,让我分别回答:

    1. 如何使用 microprofile openapi 记录错误: 使用 api 响应和操作描述是您所做的正确方法,您可以包含错误的扩展描述以及与相关联的特定 Http 错误代码每个如果你想要。此注释应存在于 Rest Resource 中,而不是 ExceptionMapper 中。
    2. 使用微配置文件处理自定义错误或仅使用 Jax-RS 处理异常的方式: 使用 Jax-RS APIs 实现的端点知道如何自动处理 WebApplicationExceptions,通过启动具有此功能的自定义异常作为我们的父母,Jax-RS 实现会自动知道如何将您的异常映射到响应。
    3. 处理意外异常或为某些异常自定义响应:通过实现接口 ExceptionMapper,您可以根据需要进一步自定义特定异常的响应生成,但这通常不是必需的。

    处理您所解释的场景的一个常见的好策略是拥有一系列自定义异常,这些异常扩展了 WebApplicationException,您可以在其中指定响应代码和消息,或者仅使用 jax-rs 提供的那些。如果您需要通过 i18n 支持进行进一步自定义,或者提供一个包含与错误相关的详细信息的响应实体很重要,那么请实现 ExceptionMapper。

    【讨论】:

      猜你喜欢
      • 2019-07-26
      • 1970-01-01
      • 2015-08-10
      • 1970-01-01
      • 2018-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多