0

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

user990635
  • 3,979
  • 13
  • 45
  • 66
  • 1
    Why is it really bad to check message string ?, you could add "The remote server returned an error" to it too. Remember there isn't always a good, perfect, or standard way to do something. BTW you could use this for now and seek better solutions for future. – Ehsan88 Sep 01 '13 at 14:54
  • What is the InnerException type? If it is of a specific type then you can use that in a catch block. – bobbyalex May 08 '14 at 07:19

2 Answers2

0

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.

Community
  • 1
  • 1
Andreas Mattisson
  • 1,051
  • 2
  • 19
  • 39
0

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

Jumpei
  • 611
  • 5
  • 15