UseExceptionHandler by Environment

60 Views Asked by At

How can I leverage the new error handling mechanism introduced in .NET 8 while distinguishing error injection handling based on the environment? Specifically, I want to handle errors differently during development and testing in one service, and in production in another service. Both services implement the IExceptionHandler interface.

1

There are 1 best solutions below

0
Tiny Wang On

Following the offcial document and I had a test with MVC project with Program.cs like below.

using WebMvcNet8;

var builder = WebApplication.CreateBuilder(args);
if (builder.Environment.IsDevelopment()) {
    builder.Services.AddExceptionHandler<CustomExceptionHandler>();
}
// Add services to the container.
builder.Services.AddControllersWithViews();
    
var app = builder.Build();    
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}
else {
    app.UseExceptionHandler(opt => { });
}    
app.UseHttpsRedirection();
app.UseStaticFiles();    
app.UseRouting();
app.UseAuthorization();   
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");   
app.Run();

enter image description here enter image description here