What Java exception class to use for HTTP errors?

Quick answer

In Spring you have exactly what you want:

  • HttpClientErrorException - Exception thrown when an HTTP 4xx is received.
  • HttpServerErrorException - Exception thrown when an HTTP 5xx is received.

And a recommended practice

Minimally, you should differentiate exceptions related to business logic (e.g., insufficient balance, email address is not valid) from other exceptions (e.g., server not available, unsupported media type, SQLException).

In our REST API, we have a library for Java clients that parses responses and throws only three different exceptions:

  • 400, 401, 403, 404, 409, 422: throw MyBusinessException, which contains a message that can be shown to the end user. The message comes in the response body (exception handling on the service side), but if not present we have a default message specific to each status code.
  • 405, 412, 415: throw HttpClientErrorException with a message that is specific to each status code.
  • other 4xx codes: throw HttpClientErrorException with a generic message.
  • 5xx codes: throw HttpServerErrorException with a generic message.

All these exceptions are unchecked.


Check out the page on Exception Handling for HttpClient

To answer your question though there appears to be an org.apache.commons.httpclient.HttpException class that is probably a good fit.

If you do need a custom exception class for this I would think java.io.IOException would be the correct super class to use.


If it's not an Exception in HttpClient design philosophy, but an Exception in your code, then create your own Exception classes. ( As a subclass of org.apache.commons.httpclient.HttpException )