What Java exception class to use for HTTP errors?

I am using Apache HttpClient and would like to communicate HTTP errors (400 Bad Request, 404 Not Found, 500 Server Error, etc.) via the Java exception mechanism to the calling code. Is there an exception in the Java standard library or in a widely used library that would be appropriate to use or to subclass for this purpose?

The alternative is to check status return codes. This appears to be the HttpClient design philosophy, but since these errors are truly exceptional in my app, I would like to have the stack trace and other nice exception things set up for me when they happen.

Asked by: Wilson910 | Posted: 21-01-2022

Answer 1

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 )

Answered by: Byron133 | Posted: 22-02-2022

Answer 2

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.

Answered by: Brad112 | Posted: 22-02-2022

Answer 3

Quick answer

In Spring you have exactly what you want:

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.

Answered by: Tess152 | Posted: 22-02-2022

Answer 4

I'd say this depends on what you are using the HTTPClient for. For example, the PayPal SDK uses HttpClient to transmit API calls to the PayPal server, but fails to check the HTTP response code when it's done. I patched my copy so that if the response code isn't 200 it throws a PayPal FatalException, with an appropriate message. That's because the caller isn't interested in the HTML or any of the details of this HTTP post, and isn't even interested in the fact that we're using HTTP as a transport. If the call is successful then the body of the response contains transaction details, which are extracted and placed into a response object; otherwise it contains HTML which is useless. HTTP is just the transport in this case, so certain response codes indicate errors which can be reported using exceptions. Because this is part of the PayPal SDK, I used a PayPal Exception class. In some other system or library, I'd use a subtype of whatever exceptions that library already uses. For example, if I were writing a GMail library, which accesses GMail accounts, I'd probably create a GMailException class, and subclass that for the different kinds of exceptions the library runs into. Alternatively, you can use something like IOException.

The reason HttpClient makes you check response codes is because the response may be useful even if the response code is not 200. Some websites put useful text on a 404 page, either providing something useful for the user to do, or a search form, or just a helpful error message. Depending on your use case you may want to just show the response content rather than throw an exception.

Answered by: Kelvin166 | Posted: 22-02-2022

Answer 5

I found this exception on Apache HTTP Client 4.5.7:

import org.apache.http.client.HttpResponseException;

StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() != 200) {
    throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());

The sample of result is:

Exception in thread "main" org.apache.http.client.HttpResponseException: status code: 400, reason phrase: Bad Request

Answered by: Aida704 | Posted: 22-02-2022

Answer 6

There is org.apache.commons.httpclient.HttpException if you want a library exception. We have also sometimes created our own for specific purposes, both creating an exception for specific HTTP status codes and a generic one for and unexpected status code.

Answered by: Kirsten117 | Posted: 22-02-2022

Similar questions

java - sql exception errors

i am trying to execute a sql command from a java program..i dont have any errors regarding this code..but i am facing connection refusals from the database.. import java.sql.*; public class DBCreateTable { public static void main(String args[]) throws Exception { DriverManager.registerDriver (new Oracle.jdbc.driver.OracleDriver()); Connection con=DriverManager.getConnection( ...

java - Exception when not finding

What is the rationale behind throwing an exeption in JPA, when something can't be found? Added: This behaviour was seen in EJB2, and has as far been removed from EJB3 - but... It remains when calling Query#getSingleResult() which throws a NoResultException. Normally I would not e...

exception - Best way to return status flag and message from a method in Java

I have a deceptively simple scenario, and I want a simple solution, but it's not obvious which is "most correct" or "most Java". Let's say I have a small authenticate(Client client) method in some class. The authentication could fail for a number of reasons, and I want to return a simple boolean for control flow, but also return a String message for the user. These are the possibilities I can think of:

Which Java exception should I use?

Let's assume I'm a complete lazy bum and I don't want to invest the several dozen keystrokes needed for my own exception class (it's not utterly important which gets used, really). However, to pretend I'm following good practices here, I want a pre-existing one that best fits my situation. Problem: I need to throw an exception when my class's constructor receives an object in its parameters that i...

java - throws Exception in finally blocks

Is there an elegant way to handle exceptions that are thrown in finally block? For example: try { // Use the resource. } catch( Exception ex ) { // Problem with the resource. } finally { try{ resource.close(); } catch( Exception ex ) { // Could not close the resource? } } How do you avoid the try/catch in the f...

In Java, when should I create a checked exception, and when should it be a runtime exception?

This question already has answers here:

java - SQL exception when trying make an prepared statement

I'm trying to pass the following String to a PreparedStatement: private static final String QUICK_SEARCH = "select * from c where NAME like '% ? %'"; However, I get an SQL exception that the bind variable is missing. Any suggestions?

Doubt in exception handling and finally block in java

Can you tell the idea of how to doing it? Code : public void main(String[] args) { try { //Some Exception throws here } catch(SomeException se) { se.printStackTrace(); } finally { try { //SomeException1 throws here } catch(SomeException1 se1) { se.printStackTrace(); //Control is getting stop in this bloc...

java - Exception occurs with JAX-RPC handler

I have some SOAP webservices build with JAX-RPC. These work fine. But as soon as I add a handler, I get an exception. When the binding is removed from the webservices.xml, everything works fine again. The weird thing is, the handler itself isn't included in the stacktrace of the exception. I also noticed, the init and getHeaders methods of the handler are called, before the exception is r...

java - exception when parsing multipart form data

I am trying to handle a file upload, and I'm using the com.oreilly.servlet.multipart.MultipartParser class to parse the posted data (in cos.jar). However, when I call the constructor for MultipartParser, I get this exception: java.io.IOException: Corrupt form data: premature ending at com.oreilly.servlet.multipart.MultipartParser.<init>(MultipartParser.java:166) at com.oreilly.servlet.multipa...

java - Help with an Exception

Encounter the following exception. Anyone have any idea how to resolve this? Or what is the issue exactly. [#|2009-03-03T10:41:18.079+0800|SEVERE|sun-appserver-pe8.2|ilog.rules.teamserver.model.IlrGlobalCache|_ThreadID=12;|java.rmi.ServerException: RemoteException occurred in server thread; nested exception is: java.rmi.RemoteException: nested exception is: java.sql.SQLException: Error in allocating a co...

Still can't find your answer? Check out these amazing Java communities for help...

Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)