Search code examples
javajacksonresteasyswagger-codegen

Swagger Codegen Resteasy - catch Deserialization Errors


i generated a server stub for my jax-rs resteasy api and just started using the stub by trying to add Stuff to the MyServiceApiServiceImpl class. I work with swagger-codegen v2.3.1.

The generated Code for my Endpoint looks like this:

@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();
  }
}

Since the request body is parsed into the MatchRequest-Object, it throws an unhandled exception if something goes wrong during the deserialization. This happens outside this function and everything i do there won't be called in this case.

The default catch for an exception looks like this:

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])

Is there a way to catch deserialization exceptions without changing something inside the generated code?


Solution

  • You can do something like this: https://howtodoinjava.com/resteasy/exception-handling-in-jax-rs-resteasy-with-exceptionmapper/

    Maybe this code will help:

    @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();
        }
    }
    

    You need to create a ExceptionMapper and handle that error there. The Jackson deserialization layer is placed before your RegelauswertungApiServiceImpl is called, therefore you never will be able to handle this error inside that RegelauswertungApiServiceImpl class.