用于 HTTP 错误的 Java 异常类是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/212239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What Java exception class to use for HTTP errors?
提问by Steven Huwig
I am using Apache HttpClientand 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?
我正在使用 Apache HttpClient并希望通过 Java 异常机制将 HTTP 错误(400 错误请求、404 未找到、500 服务器错误等)传达给调用代码。Java 标准库或广泛使用的库中是否有适合为此目的使用或子类化的例外?
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.
另一种方法是检查状态返回代码。这似乎是 HttpClient 的设计理念,但由于这些错误在我的应用程序中确实非常特殊,我希望在它们发生时为我设置堆栈跟踪和其他不错的异常内容。
采纳答案by asalamon74
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 )
如果它不是 HttpClient 设计理念中的 Exception,而是您代码中的 Exception,那么创建您自己的 Exception 类。(作为 org.apache.commons.httpclient.HttpException 的子类)
回答by Instantsoup
There is org.apache.commons.httpclient.HttpExceptionif 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.
如果你想要一个库异常,有org.apache.commons.httpclient.HttpException。我们有时也为特定目的创建我们自己的,既为特定 HTTP 状态代码创建异常,也为意外状态代码创建通用异常。
回答by Mike Deck
Check out the page on Exception Handling for HttpClient
查看HttpClient 异常处理页面
To answer your question though there appears to be an org.apache.commons.httpclient.HttpExceptionclass that is probably a good fit.
要回答您的问题,尽管似乎有一个org.apache.commons.httpclient.HttpException类可能很合适。
If you do need a custom exception class for this I would think java.io.IOExceptionwould be the correct super class to use.
如果您确实需要一个自定义异常类,我认为java.io.IOException将是正确的超类使用。
回答by u7867
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.
我会说这取决于您使用 HTTPClient 的目的。例如,PayPal SDK 使用 HttpClient 将 API 调用传输到 PayPal 服务器,但在完成时无法检查 HTTP 响应代码。我修补了我的副本,以便如果响应代码不是 200,它会抛出一个 PayPal FatalException,并带有适当的消息。这是因为调用者对 HTML 或此 HTTP 帖子的任何细节不感兴趣,甚至对我们使用 HTTP 作为传输的事实也不感兴趣。如果调用成功,则响应正文包含事务详细信息,这些详细信息被提取并放入响应对象中;否则它包含无用的 HTML。在这种情况下,HTTP 只是传输,因此某些响应代码指示可以使用异常报告的错误。因为这是 PayPal SDK 的一部分,所以我使用了 PayPal Exception 类。在其他一些系统或库中,我会使用库已经使用的任何异常的子类型。例如,如果我正在编写一个访问 GMail 帐户的 GMail 库,我可能会创建一个 GMailException 类,并为库遇到的不同类型的异常创建子类。或者,您可以使用类似异常。
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.
HttpClient 让你检查响应代码的原因是,即使响应代码不是 200,响应也可能有用。一些网站将有用的文本放在 404 页面上,要么提供对用户有用的东西,要么提供搜索表单,或者只是一个有用的错误信息。根据您的用例,您可能只想显示响应内容而不是抛出异常。
回答by Paulo Merson
Quick answer
快速回答
In Spring you have exactlywhat you want:
在春天你究竟你想要什么:
- HttpClientErrorException- Exception thrown when an HTTP 4xx is received.
- HttpServerErrorException- Exception thrown when an HTTP 5xx is received.
- HttpClientErrorException- 收到 HTTP 4xx 时抛出异常。
- HttpServerErrorException- 收到 HTTP 5xx 时抛出异常。
And a recommended practice
和推荐的做法
Minimally, you should differentiate exceptions related to business logic (e.g., insufficient balance, email address is not valid) from otherexceptions (e.g., server not available, unsupported media type, SQLException).
至少,您应该将与业务逻辑相关的异常(例如,余额不足、电子邮件地址无效)与其他异常(例如,服务器不可用、不受支持的媒体类型、SQLException)区分开来。
In our REST API, we have a library for Java clients that parses responses and throws only three different exceptions:
在我们的 REST API 中,我们有一个 Java 客户端库,用于解析响应并仅抛出三种不同的异常:
- 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.
- 400, 401, 403, 404, 409, 422: throw
MyBusinessException
,其中包含可以显示给最终用户的消息。该消息出现在响应正文中(服务端的异常处理),但如果不存在,我们有一个特定于每个状态代码的默认消息。 - 405, 412, 415:抛出
HttpClientErrorException
特定于每个状态代码的消息。 - 其他 4xx 代码:抛出
HttpClientErrorException
通用消息。 - 5xx 代码:抛出
HttpServerErrorException
通用消息。
All these exceptions are unchecked.
所有这些异常都未经检查。
回答by Wendel
I found this exception on Apache HTTP Client 4.5.7:
我在 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