22

How do I get to the content of Refit.ApiException?

Depending on what the inner content is, I want to let the user know how to proceed. So I see that thrown exception has the following content ...

Content "{\"error\":\"invalid_grant\",\"error_description\":\"The user name or password is incorrect.\"}"

The question is, how do I access that?

Flagbug
  • 2,093
  • 3
  • 24
  • 47
crazyDiamond
  • 1,070
  • 2
  • 16
  • 20
  • 1
    Going through the RestService class https://github.com/paulcbetts/refit/blob/master/Refit/RestService.cs figured out I could use the GetContentAs method ((Refit.ApiException)ex).GetContentAs>() – crazyDiamond Mar 03 '15 at 16:42

4 Answers4

15

You can add one catch block for ApiException. and you can get content from this catch block. See below:

catch (ApiException ex)
{
    var content = ex.GetContentAs<Dictionary<String, String>>();
    Debug.WriteLine(ex.Message);
}
Pavan V Parekh
  • 1,906
  • 2
  • 19
  • 36
  • 1
    After catching the exception and having the content, you need to go through the dictionary and get the message: `var message = content.FirstOrDefault(pair => pair.Key == "ExceptionMessage").Value;` – EspressoCode Jun 30 '22 at 19:36
  • var message = content.Result.FirstOrDefault(pair => pair.Key == "ExceptionMessage").Value; Watch out for result if you haven't already fetched the Result from Task – Zeeshan Badshah Aug 03 '22 at 13:12
10

Going through the RestService class https://github.com/paulcbetts/refit/blob/master/Refit/RestService.cs

figured out I could use the GetContentAs method

So just did this..

((Refit.ApiException)ex).GetContentAs<Dictionary<String, String>>()) 

to parse out the key value content.

crazyDiamond
  • 1,070
  • 2
  • 16
  • 20
6

As an extra heads-up:

GetContentAs<T>(); is now deprecated.

Use GetContentAsAsync<T>(); instead.

jari
  • 163
  • 2
  • 10
2

With the latest version of API Exception, you can use the following code for getting the API content:

public static void HandleException( Exception exception )
{
    var content = ((Refit.ApiException)exception).GetContentAsAsync<Dictionary<string, string>>();
    var message = content.Result.FirstOrDefault( pair => pair.Key == "message" ).Value;
    Debug.WriteLine(message);           
}
Anton Menshov
  • 2,266
  • 14
  • 34
  • 55