问题描述:

I need to catch "The remote server returned an error: (401) Unauthorized." exception to do another action.

The problem is, I'm not sure how to recognize it.

Right now, I'm using

catch (Exception ex)

{

}

but the exception "The remote server returned an error: (401) Unauthorized." appears inside the "InnerException" and the "Message", so no status code or anything.

How can I track this specific exception?

I am using GoogleDrive SDK if it's relevant.

Tried to use this:

catch (GoogleApiRequestException e) {

if (e.HttpStatusCode == HttpStatusCode.Unauthorized) {

// Credentials have been revoked.

// TODO: Redirect the user to the authorization URL.

throw new NotImplementedException();

}

}

But e.HttpStatusCode was 0, so it didn't recognize it.

I guess I can use

if(ex.Message.Contains("401"))

But it's really bad

网友答案:

There has been an issue with google-api-dotnet-client code on version 1.7. If you are using this version I encourage you to update to latest.

If you look at this link: Google.Apis.Email_Migration_v2 you will see that there has been a ticket on this bug.

Here is a tutorial and code-examples that shows how this error shall be taken cared of when the API is corrected: https://developers.google.com/drive/web/handle-errors

If you still get the same problem, I also suggest the same solution to you problem to check for the 401 error in the string.

网友答案:

The GoogleApiRequestException class has a property Code not HttpStatusCode. So you can check Code like below.

if(e.Code.Equals("401"))  

I refered here.
https://developers.google.com/drive/web/handle-errors#catching_exceptions_with_client_libraries

相关阅读:
Top