javarestexceptionjerseythrow

Exception for REST services for invalid input requests


I am currently developing REST services and throwing BadRequestException for all of the following,

1. Path parameter is invalid
2. Query parameter is invalid
4. Input request object has missing attributes 

Is there any specific exceptions for each case like InvalidParameterException or so..? Is there any documentation available to learn which exceptions should be thrown on what situations?


Solution

  • I think it's a personal decision and the answer will depend on your needs to have more detailed expceptions or not.

    There are two ways to handle errors with JAX-RS:

    Throwing a WebApplicationException

    That's the approach you are using, which allows you to map exceptions that extend WebApplicationException to HTTP error responses.

    I think throwing a BadRequestException is just fine for all the situations mentioned in your question. Just remember adding a detailed message explaining what was wrong.

    If you need a more specific exception, you could consider extending the BadRequestException or maybe the ClientErrorException. The new exceptios could encapsulate the message which explains what the problem with the request. It's up to your needs.

    For more details on the exceptions provided by the JAX-RS API, have a look at the javax.ws.rs package documentation. If they do not fit your needs, just extend them and create your specific exceptions.

    Using an ExceptionMapper

    In other cases it may not be appropriate to throw instances of WebApplicationException, or classes that extend WebApplicationException, and instead it may be preferable to map an existing exception to a response. For such cases it is possible to use a custom exception mapping provider.

    Consider, for example, you decide to throw an IllegalArgumentException whenever you received an inapropriate value for your query or path parameters. You can create an ExceptionMapper to map the IllegalArgumentException to a response with the 400 status code:

    @Provider
    public class IllegalArgumentExceptionMapper 
                 implements ExceptionMapper<IllegalArgumentException> {
    
        @Override
        public Response toResponse(IllegalArgumentException exception) {
            return Response.status(400).entity(exception.getMessage())
                           .type("text/plain").build();
        }
    }
    

    For more details, have a look at the Jersey documentation.