I was pleased to read that Microsoft were introducing Error page support for Blazor in net8.0, see: https://learn.microsoft.com/en-us/aspnet/core/release-notes/aspnetcore-8.0?view=aspnetcore-8.0#error-page-support
So thought I would try it out. I created a new solution using the 'Blazor Web App' template, using the Server Interactive render mode and including the sample pages.
I then changed the Program.cs code to:
if (app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
So that the error page should be used in development mode.
I then changed the Counter.razor IncrementCount method to:
private void IncrementCount()
{
if (currentCount == 5)
{
throw new IndexOutOfRangeException("Counter can only go up to 5");
}
currentCount++;
}
I ran the website in my local environment, clicking the counter Click me button. When it got to 5 the exception was thrown but rather than showing the error message it showed the usual blazor-error-ui message:
How do I get my Blazor application to show the error page instead?
As far as I know,the middleware is used to handle http request,when you click the button,you are interacting with server via Signalr instead of Http(you would only send httprequest the first time you reach the Blazor app),the middleware won't work here.
You could add a middleware as follow,assuming you get error on the http request at first
app.Use(async (context, next) =>
{
if (!context.Request.Path.Value.Contains("Error"))
{
throw new Exception("e");
}
await next.Invoke();
});
Now you would see the Error component:
For the error in your component,you should follow this document