如何从IO异常中检测404响应代码?

前端之家收集整理的这篇文章主要介绍了如何从IO异常中检测404响应代码?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
您如何从IO异常中检测404.我可以只搜索错误消息“404”,但这是正确的方法吗?有什么更直接的吗?
  1. import com.google.api.services.drive.model.File;
  2. import com.google.api.services.drive.Drive.Files.Update;
  3. import com.google.api.services.drive.Drive;
  4.  
  5.  
  6. File result = null;
  7.  
  8. try {
  9.  
  10. update = drive.files().update(driveId,file,mediaContent);
  11. update.setNewRevision(true);
  12.  
  13. result = update.execute();
  14.  
  15. } catch (IOException e) {
  16.  
  17. Log.e(TAG,"file update exception,statusCode: " + update.getLastStatusCode());
  18. Log.e(TAG,e: " + e.getMessage());
  19.  
  20. }
  21.  
  22. Log.e(TAG,statuscode " + update.getLastStatusCode());
  23.  
  24. 03-03 05:04:31.738: E/System.out(31733): file update exception,statusCode: -1
  25. 03-03 05:04:31.738: E/System.out(31733): file update exception,e: 404 Not Found
  26. 03-03 05:04:31.738: E/System.out(31733): "message": "File not found: FileIdRemoved",

答:以下Aegan的评论是正确的,事实证明你可以将异常子类化为GoogleJsonResponseException并从那里获取状态代码.在这种情况下,答案最终取决于我使用的是GoogleClient,它生成包含状态代码的IO Exception的子类.

例:

  1. Try{
  2. ...
  3. }catch (IOException e) {
  4.  
  5. if(e instanceof GoogleJsonResponseException){
  6. int statusCode = ((GoogleJsonResponseException) e).getStatusCode();
  7. //do something
  8. }
  9. }

解决方法

处理HttpResponseException:
  1. catch (HttpResponseException hre) {
  2. if (hre.getStatusCode() == 404) {
  3. // TODO: Handle Http 404
  4. }
  5. }

详情:
AbstractGoogleClientRequest创建例外See source code

execute方法调用executeUnparsed.emandUnparsed用newExceptionOnError创建异常.在那里你会看到,它抛出一个HttpResponseException(它是IOException的子类)

猜你在找的Android相关文章