I'm working on a Blazor app that consume ASP.Net Core Web API using HttpClient. Here is how the calling service looks like:
public async Task<IEnumerable<TEntity>> GetAllAsync()
{
return await httpClient.GetJsonAsync<TEntity[]>(APIUrl);
}
public async Task<TEntity> AddAsync(TEntity entity)
{
return await httpClient.PostJsonAsync<TEntity>(APIUrl, entity);
}
And the Web API looks like
[HttpGet]
public async Task<ActionResult> Get()
{
try
{
return Ok(await repository.GetAllAsync());
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError,ex);
}
}
[HttpPost]
public async Task<ActionResult<TEntity>> Post(TEntity entity)
{
try
{
var result = await repository.AddAsync(entity);
return CreatedAtAction(nameof(Get), result.Id, result);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex);
}
}
Now, if the Web API throws an exception, or if there is Authorization error. How do I handle it in my calling Service and show user the error message.