i have example use IExeceptionHandler in NET 8
Class ExceptionHandler
public class ExceptionHandler : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
{
switch (exception)
{
case ArgumentNullException:
await httpContext.Response.WriteAsJsonAsync(new ProblemDetails
{
Status = StatusCodes.Status400BadRequest,
Type = exception.GetType().Name,
Title = exception.Message,
Detail = exception.Message,
Instance = $"{httpContext.Request.Method} {httpContext.Request.Path}"
});
break;
default:
await httpContext.Response.WriteAsJsonAsync(new ProblemDetails
{
Status = StatusCodes.Status500InternalServerError,
Type = exception.GetType().Name,
Title = ("Internal server error"),
Detail = ("Internal server error"),
Instance = $"{httpContext.Request.Method} {httpContext.Request.Path}"
});
break;
}
return true;
}
}
Config in Program.cs
builder.Services.AddExceptionHandler<ExceptionHandler>();
builder.Services.AddProblemDetails();
...
app.MapGet("/weatherforecast", () =>
{
throw new ArgumentNullException();
});
But i got an error like image:
enter image description here
Look like my ExceptionHandler not working
Please help me to solve this problems.
I have create code example but it not work
New contributor