处理HTTP错误调用的最佳实践
我将这个问题发布到 Android 开发者小组,但我想将其发布到这里,以供其他可能面临像我这样的设计问题的人使用:
我正在寻找有关如何处理 HTTP 错误的习惯用法或范例。
基本上,
我有一个在后台线程中运行的 AsyncTask,它调用我的一个静态方法,称为executeRequest()。
这一切都是在 doInBackground() 部分完成的。 executeRequest() 抛出两种类型的异常。所有通信错误的 IOException 和 ServerErrorResponse 异常(这是我自己的异常)。例如,如果客户端向服务器发送了一些错误的内容,整个 HTTP 工作正常但服务器抱怨(也许我传递了无效的参数或 ID),则可能会发生这种情况。
因此,我所做的是将结果包装在我自己的“结果对象”中。
在 onPostExecute() 中,我检查结果是否失败,然后尝试在 UI 线程中处理它。然而,我现在必须开始做,
Exception e = result.getException();
if (e != null) {
if (e instanceof IOException) { //network error
//handle network error here
} else if (e instanceof ServerErrorResponseException) {
//handle server error response here
}
正如你所看到的,这变得很烦人,对于每个新的异常,我必须使用 instanceof 检查它。有没有办法解决这个问题或者我可以遵循的设计来避免这种情况?我希望在 UI 线程中处理异常,以防我向用户显示对话框或其他内容。
有什么想法吗?
I posted this question to the Android developer groups but I wanted to post it here for other people who might be facing a design problem like me:
I was looking for an idiom or paradigm on how to handle HTTP errors.
Basically,
I have an AsyncTask that runs in a background thread, that calls a static method of mine called executeRequest().
This is all done in the doInBackground() part. There are two types of exceptions that be thrown by executeRequest(). An IOException for all communication errors and a ServerErrorResponse exception which is my own exception. This can occur if for example the client sent something bad to the server, the whole HTTP worked but the server complained (perhaps I passed an invalid parameter or id).
So, what I have done is wrap the result in a "result object" of my own.
In onPostExecute() I check if the result was failed and then I try to handle it in the UI thread. However, I now have to start doing
Exception e = result.getException();
if (e != null) {
if (e instanceof IOException) { //network error
//handle network error here
} else if (e instanceof ServerErrorResponseException) {
//handle server error response here
}
As you can see this is becoming annoying, For every new exception I have to check it using instanceof. Is there a way around it or a design I could follow to avoid this? I want the exceptions to be processed in the UI thread in case I show a dialog box or something to the user.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这只是几个选项中的一个:
创建一个像现在这样的接口
,在您的
onPostExecute
中执行类似的操作如果您愿意,您可以在活动外部创建结果处理程序(此选项更好,以便避免跨活动的代码重复)
最后,
handleWith
实现:This is only one option, out of several:
Create an interface like
Now, in your
onPostExecute
do something likeIf you prefer, you can create the result handler outside your activity (this option is better in order to avoid code duplication across activities)
Finally,
handleWith
implementation: