IExceptionHandler not call when throw new Exception NET 8

  Kiến thức lập trình

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

Hen Joey is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website Kho Theme wordpress Kho Theme WP Theme WP

LEAVE A COMMENT