Reputation: 6597
I'm trying to figure out where I went wrong. I want to catch 404 errors that come to my api. I have the middleware setup, but the exception never occurs when I try to hit the page that doesn't exist.
public async Task Invoke(HttpContext context)
{
try
{
await _requestDelegate.Invoke(context);
}
catch (Exception exception)
{
await HandleExceptionAsync(context, exception);
}
}
//in startup
app.UseMiddleware<ExceptionHandler>();
and I register it in the startup, its the first thing I do to ensure it handles the rest.
Upvotes: 1
Views: 954
Reputation: 12420
Sounds like you want UseStatusCodePagesWithReExecute
to catch the 404 and modify the response, log, ect.
//Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
app.UseStatusCodePagesWithReExecute("/error/", "?statusCode={0}");
...
}
//SomeController.cs
public IActionResult Error(int? statusCode = null)
{
if(statusCode == 404) return new ObjectResult(new { message = "404 - Not Found" });
...
}
Upvotes: 2