您如何从IO异常中检测404.我可以只搜索错误消息“404”,但这是正确的方法吗?有什么更直接的吗?
import com.google.api.services.drive.model.File; import com.google.api.services.drive.Drive.Files.Update; import com.google.api.services.drive.Drive; File result = null; try { update = drive.files().update(driveId,file,mediaContent); update.setNewRevision(true); result = update.execute(); } catch (IOException e) { Log.e(TAG,"file update exception,statusCode: " + update.getLastStatusCode()); Log.e(TAG,e: " + e.getMessage()); } Log.e(TAG,statuscode " + update.getLastStatusCode()); 03-03 05:04:31.738: E/System.out(31733): file update exception,statusCode: -1 03-03 05:04:31.738: E/System.out(31733): file update exception,e: 404 Not Found 03-03 05:04:31.738: E/System.out(31733): "message": "File not found: FileIdRemoved",
答:以下Aegan的评论是正确的,事实证明你可以将异常子类化为GoogleJsonResponseException并从那里获取状态代码.在这种情况下,答案最终取决于我使用的是GoogleClient,它生成包含状态代码的IO Exception的子类.
例:
Try{ ... }catch (IOException e) { if(e instanceof GoogleJsonResponseException){ int statusCode = ((GoogleJsonResponseException) e).getStatusCode(); //do something } }
解决方法
处理HttpResponseException:
catch (HttpResponseException hre) { if (hre.getStatusCode() == 404) { // TODO: Handle Http 404 } }
详情:
AbstractGoogleClientRequest创建例外See source code
execute
方法调用@L_404_2@.emandUnparsed用newExceptionOnError
创建异常.在那里你会看到,它抛出一个HttpResponseException(它是IOException的子类)