How to catch the exception from middleware in Razor page app?

zbx888

New member
Joined
Aug 17, 2023
Messages
2
Programming Experience
5-10
I have intranet.net core razor app with default exception handling setting as follows: if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); app.UseHsts(); }

I have one custom middleware to deal with Windows Authentication with Identity membership and check the user id application user. If not the application user, app throws one exception as follows:

if (user != null)
{
await signInManager.SignInAsync(user, true);
context.User = await signInManager.CreateUserPrincipalAsync(user);
_logger.LogInformation($"User with id {user.Id}, name {user.UserName} successfully signed in");

// Workaround
context.Items["IntranetUser"] = user;
}
else
{
_logger.LogInformation($"User cannot be found in identity store.");
throw new System.InvalidOperationException($"user not found.");
}

In production, the exception is never catched instead of 500 error. How to solve this issue? Thanks!

1692298960678.png
 
Did you verify that routing to "/Error" actually successfully shows a page? Perhaps the error 500 is due to the failure to find such a path within your app.
 
Did you verify that routing to "/Error" actually successfully shows a page? Perhaps the error 500 is due to the failure to find such a path within your app.

Thank you for your response. In Program.cs, system triggers the error app.UseExceptionHandler("/Error"); under production evniroment but never goes to Error page. What is wrong?
 
Do you know that the error page works?
 
In Program.cs, system triggers the error app.UseExceptionHandler("/Error"); under production evniroment

On re-reading this, are you saying that making this call itself causes the error -- in your words: "triggers the error"? If so then of course the error page won't be shown because the act of trying to setup the error handler page failed.
 

Latest posts

Back
Top Bottom