您如何从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, "file update exception, e: " + e.getMessage());
}
Log.e(TAG, "file update exception, 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",
Run Code Online (Sandbox Code Playgroud)
答:以下Aegan的评论是正确的,事实证明你可以将异常子类化为GoogleJsonResponseException并从那里获取状态代码.在这种情况下,答案最终取决于我使用的是GoogleClient,它生成包含状态代码的IO Exception的子类.
例:
Try{
...
}catch (IOException e) {
if(e instanceof GoogleJsonResponseException){
int statusCode = ((GoogleJsonResponseException) e).getStatusCode();
//do something
}
}
Run Code Online (Sandbox Code Playgroud)
处理HttpResponseException:
catch (HttpResponseException hre) {
if (hre.getStatusCode() == 404) {
// TODO: Handle Http 404
}
}
Run Code Online (Sandbox Code Playgroud)
细节:
AbstractGoogleClientRequest创建例外.请参阅源代码
execute方法调用executeUnparsed.executeUnparsed创建异常newExceptionOnError.在那里你会看到,它抛出一个HttpResponseException(这是一个子类IOException)