简体   繁体   中英

C# .net Core catch custom Exception

Where is my fault?

I have a class type Exception

public class ApiException : Exception {
  public ApiException(string message) : base(message) {
  }
}

In some situations I call throw new ApiException("Message"); For example here:

public static async Task<string> ValidateToken(string token) {
  Dictionary<string, string> values = new Dictionary<string, string> {
    { "token", token}
  };

  FormUrlEncodedContent content = new FormUrlEncodedContent(values);
  HttpResponseMessage response = await client.PostAsync(Globals.sso, content);

  string responseString = await response.Content.ReadAsStringAsync();

  if (response.IsSuccessStatusCode) {
    TokenResp result = JsonConvert.DeserializeObject<TokenResp>(responseString);
    if (result.Token != token)
      throw new ApiException("Token is invalid");
  } else {
    NonFieldResponse resp = JsonConvert.DeserializeObject<NonFieldResponse>(responseString);
    string msg = null;

    foreach (string message in resp.non_field_errors) {
      if (msg != null) msg += ", ";
      msg += message;
    }

    throw new ApiException(msg);
  }

In somewhere I need to catch exceptions like here:

try {
  Type = ValidateToken(token).Result;
} catch (ApiException ae) {
  Console.WriteLine(ae.Message);
} catch (Exception e) {
  Console.WriteLine(e.Message);
}

But catch (ApiException ae) doesn't happens, always catched simple Exception (where e.GetType() is AggregateException and e.InnerException.GetType() is ApiException ).

How to catch my exception?

-- edit, after seeing code that is even more real:

  • When your caller is not async, be careful because this can cause deadlocks:
// Type = ValidateToken(token).Result;
   Type = ValidateToken(token).GetAwaiter().GetResult();
  • when you caller method is also async:
Type = await ValidateToken(token); 

Both of these will 'unwrap' the aggregate exception.
Your custom exception is of course one of the InnerExceptions of that AggregateException.

You ApiException will not get caught properly unless you await the ValidateToken() call. When you use:

Type = ValidateToken(token)Result;

instead of:

Type = await ValidateToken(token);

Your exceptions will be wrapped in an AggregateException .

Using await properly will allow the proper exception to get caught.

Use this:

try {
  Type = await ValidateToken(token);
} catch (ApiException ae) {
  Console.WriteLine(ae.Message);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM