What to use on failures and errors: WebApplicationException vs Response?

I am working on Rest service and I am confused on crashes / errors if I use Response

or WebApplicationException

?

Below is an example where I use Response to return a 400 Bad Request error message along with a JSON response of what went wrong.

@GET
@Path("/data")
@Produces(MediaType.APPLICATION_JSON)
public Response getData(@Context UriInfo uriInfo) {
    String client = getClientId();
    if (client == null || client.isEmpty()) {
        return Response.status(HttpServletResponse.SC_BAD_REQUEST)
                .entity("{\"error\": \"client id is null or empty\"}").build();
    }

    // some code and return succesfull response

    return Response
            .status(HttpServletResponse.SC_OK)
            .entity(resp.getResponse()).build();
}

      

What's the right thing to do here? If I need to use WebApplicationException

, then how can I use it to return a 400 Bad Request error message along with a JSON response

+3


source to share


1 answer


In this particular case, whether the Response

mapped exception should be returned or thrown, I say, is just a matter of preference. But there are times when returning is Response

not possible, for example if you are bound to an interface contract where the return type is not Response

, or you are not in the context of a resource method, say in a filter or interceptor.



If you need to throw an exception and it is impossible to return Response

(or you just throw an exception), if you look at the constructors WebApplicationException

, you will notice that it has a constructor except for a Response

. This is really the only way to add a body if you've thrown an exception (unless you are using mapper ).

+2


source







All Articles