简体   繁体   中英

Blazor handle the error in the response from Web Api

There are two applications:

  1. Blazor server-side
  2. Web API (written long ago)

WebApi action

public async Task<object> GetAllAsync(...)
{
   ...
   // Какая то проверка
   throw new Exception("Что то пошло не так");
   ...
}

An example view of a method in a client application(Blazor server-side)

    public async Task GetAllAsync()
    {
            var httpClient = clientFactory.CreateClient();
            var responseMessage = await httpClient.GetAsync($"{address}/api/foo");

            if (responseMessage.IsSuccessStatusCode)
            {
                // successfully
            }
            else
            {
                // How to get the error message here?
            }
        }
    }

The question is: how to properly handle this kind of error from API?

ps

var exception = await responseMessage.Content.ReadAsAsync<HttpError>();

HttpError pulls a dependency with .NetFramework 4.6 (but initially I use .net core 3 preview)

The HttpContent class does not define a ReadAsAsync method. This is an extension method which I believe is considered obsolete,and is no longer supported. You may use ReadAsStringAsync(), ReadAsStreamAsync(), etc.

Example how to serialize the exception content to string:

var exception = await responseMessage.Content.ReadAsStringAsync();

The following code snippet demonstrates how to use HttpContent.ReadAsByteArrayAsync() to serialize the HTTP content to a byte array as an asynchronous operation, and then parse the array to a type you may define to hold the http error (something similar to the HttpError object, which you should not use, but simpler).

var responseBytes = await responseMessage.Content.ReadAsByteArrayAsync();

Note: Change the type specifier T to your custom type, or use built-in types such as string, according to your design...

JsonSerializer.Parse<T>(responseBytes, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });

Hope this helps

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