【问题标题】:Swagger Codegen Resteasy - catch Deserialization ErrorsSwagger Codegen Resteasy - 捕获反序列化错误
【发布时间】:2018-08-30 13:49:54
【问题描述】:

我为我的 jax-rs resteasy api 生成了一个服务器存根,并通过尝试将 Stuff 添加到 MyServiceApiServiceImpl 类开始使用存根。我与swagger-codegen v2.3.1 合作。

为我的 Endpoint 生成的代码如下所示:

@RequestScoped
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2018-08-30T14:30:35.907+02:00")
public class RegelauswertungApiServiceImpl implements RegelauswertungApiService {
      public Response regelauswertung(MatchRequest body,SecurityContext securityContext)
      throws NotFoundException {
      // do some magic!
      return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build();
  }
}

由于请求正文被解析为MatchRequest-Object,如果在反序列化过程中出现问题,它会抛出未处理的异常。这发生在这个函数之外,在这种情况下,我在那里所做的一切都不会被调用。

异常的默认捕获如下所示:

com.fasterxml.jackson.databind.JsonMappingException: Unexpected character (',' (code 44)): expected a value at [Source: (io.undertow.servlet.spec.ServletInputStreamImpl); line: 24, column: 30] at [Source: (io.undertow.servlet.spec.ServletInputStreamImpl); line: 24, column: 11] (through reference chain: com.dai.asfopt.service.web.swagger.model.MatchRequest["fahrzeuge"]->java.util.ArrayList[0]->com.dai.asfopt.service.web.swagger.model.Fahrzeug["arbeitsplatzlasten"]->java.util.ArrayList[0])

有没有办法在不更改生成代码中的某些内容的情况下捕获反序列化异常?

【问题讨论】:

  • 尝试查看 JAX-RS @Valid 注释。

标签: java jackson resteasy swagger-codegen


【解决方案1】:

你可以这样做:https://howtodoinjava.com/resteasy/exception-handling-in-jax-rs-resteasy-with-exceptionmapper/

也许这段代码会有所帮助:

@Provider
public class GlobalExceptionHandler implements ExceptionMapper<JsonMappingException > {
    @Override
    public Response toResponse(JsonMappingException exception) {
        return Response.status(Status.INTERNAL_SERVER_ERROR)
            .entity("An error deserializing the JSON")
            .type(MediaType.TEXT_PLAIN)
            .build();
    }
}

您需要创建一个 ExceptionMapper 并在那里处理该错误。 Jackson 反序列化层放置在调用 RegelauswertungApiServiceImpl 之前,因此您永远无法在 RegelauswertungApiServiceImpl 类中处理此错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-30
    • 2017-05-20
    • 2019-09-19
    • 1970-01-01
    • 2015-01-19
    • 1970-01-01
    • 2017-05-29
    相关资源
    最近更新 更多