Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle exceptions with Swagger?

I am building some test APIs using swagger (1.5) and JAX-rs with Jersey (1.13) and I m trying to implement exception handling. For example I have the following code when receiving the results from my DB (Elasticsearch)

@POST
@Path("/category")
@ApiOperation(value="returns products")
@Produces({ "application/json" })
public Response getPostCategories( 
        @ApiParam(value="keyphrase, required=true) @QueryParam("keyphrase") String keyphrase,
        @ApiParam(value="category) @QueryParam("category") String category,     
        @Context SecurityContext securityContext) 
throws WebApplicationException {        
    SearchRequest searchRequest = new SearchRequest();
    searchRequest.setKeyphrase(keyphrase);
    searchRequest.setCategory(category);

    SearchCategoryQuery categoryQuery = new SearchCategoryQuery();
    String searchResponse = null;
    try
    {           
        searchResponse = categoryQuery.searchCategory(searchRequest);
    }
    catch (WebApplicationException ex)
    {
        throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity("results no found").type(javax.ws.rs.core.MediaType.APPLICATION_JSON).build());
    }
    return Response.ok(searchResponse).build();
}

However, in the output swagger always prints the same responseenter image description here

What I need instead is to receive the error messages I specify in each exception. Any ideas?

like image 786
panipsilos Avatar asked Oct 22 '25 03:10

panipsilos


1 Answers

Swagger by itself does not handle application exceptions as yet.

You will either need to create custom Exception classes (that extend java.lang.exception) or use the existing ones (like WebApplicationException that you are already using) and make the API definition throw these errors. So basically you need to use Java/J2EE/Jersey to throw proper exceptions. Swagger UI will display them for you.

Check this link for details on REST exception handling with Spring.

like image 148
Sampada Avatar answered Oct 25 '25 09:10

Sampada



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!