I'm a bit confused with how ASPNET core API responses to the client when something goes wrong. I'm working on a ASPNET core hosted Blazor webassembly and use HttpClient to get data from Server API through controllers.
The problem is if something goes wrong on the server (in my case before reaching the controllers), it returns a 200 OK response with an html document that includes the message "An unhandled error has occurred.", which causes the the response bypass the
response.EnsureSuccessStatusCode();
or if(!response.IsSuccessStatusCode)
and cause JsonException as Deserializer cannot deserialize html document in the content.
Is this a logical behavior? Can we change the app behavior to return a 500 instead?
Or have I configured the app incorrectly somewhere?
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
CodePudding user response:
There are pretty good info here and here about customizing the error handling but the problem I had was actually a simpler mistake I had forgotten about. I had to add Accept header "application/json" to the http calls the client makes to the server API.
_httpClient.DefaultRequestHeaders.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));
in this way the server returns 500 upon any API exceptions and all Http errors can be handled in the response plus keeping the error handling pipeline for other parts of the client app.