In Blazor dealing with unexpected results from the api web server

I'm developing a fairly simple Blazor app using a lot of default template functionality, and I can't figure out how to handle an ActionResult from the server that isn't the normal return value.

On the server side I've slightly modified the default controller template to look something like this:

    public async Task<ActionResult<MyData>> GetSession(int id)
    {
        var myData= await FetchMyData(id);

        if (myData== null)
        {
            return NotFound();
        }
        return myData;
    }

That check for a null value was in the original template - it seems like a good idea so I kept it. On the client side my code looks like this:

    public async Task<MyData> GetMyData(int id)
    {
        return await Http.GetJsonAsync<MyData>("/api/MyData/" + id);
    }

It all works quite well, except the client side code doesn't handle the case where the server side returns a "NotFound()" result. It's not a show stopper, but it's driving me crazy that I don't know how to do it.

It seems that the GetJsonAsync() call on the client is silently unwrapping the return Value from the ActionResult wrapper (I guess?). Does that mean if I want to handle a NotFound condition I should be using a different httpclient function and maybe deserializing the object Value myself? If so, anyone want to volunteer an example?

Or am I missing something and there's an easier way?

It seems stupid to check for a condition on the server side just to send the client a warning that ultimately results in an unhandled exception.

Upvotes: 0

Views: 471

Answers (1)

I tried Henk Holterman's suggestion of just adding a try/catch, and it turns out the exception that was thrown had the information I wanted - that is the status being returned by the server. So what I should have done was this:

public async Task<MyData> GetMyData(int id)
{
    try
    {
        return await Http.GetJsonAsync<MyData>("/api/MyData/" + id);
    }
    catch (System.Net.Http.HttpRequestException e)
    {
        .... process the exception
    }
}

Turns out HttpRequestException has the HResult, which is what I was looking for.

Thanks Henk.

Upvotes: 1

Related Questions