最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - IExceptionHandler in ASP.NET Core 8.0 Web API - unable to debug - Stack Overflow

programmeradmin3浏览0评论

I am unable to step into the Exception handler code to see how the problem details is built and sent as response when an exception is thrown anywhere in code

public class GlobalExceptionHandler : IExceptionHandler
{
    private readonly ILogger<GlobalExceptionHandler> _logger;

    public GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger)
    {
        _logger = logger;
    }

    public async ValueTask<bool> TryHandleAsync(
        HttpContext httpContext,
        Exception exception,
        CancellationToken cancellationToken)
    {
        _logger.LogError(
            exception, "Exception occurred: {Message}", exception.Message);

        var problemDetails = new ProblemDetails
        {
            Status = StatusCodes.Status500InternalServerError,
            Title = "Server error"
        };

        httpContext.Response.StatusCode = problemDetails.Status.Value;

        await httpContext.Response
            .WriteAsJsonAsync(problemDetails, cancellationToken);

        return true;
    }
}

I have this in Program.cs. I believe I have got the placement right? Not sure why I am not able to step in. I see some fomatted exception and not the stacktrace, not sure where and how that is done.

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// Add these Lines
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
builder.Services.AddProblemDetails();


var app = builder.Build();

// Replacing this line
//app.UseExceptionHandler();
// with the following line works
  app.UseExceptionHandler("/Error");

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

For an enddpoint like ...

[HttpGet]
[Route(nameof(FileExists))]
public async Task<bool> FileExists(
    [FromQuery] string fileName, 
    [FromQuery] Guid containerId)
{

}

If fileName query parameter is not passed, the endpoint itself doesn't appear to be hit. However, some exception handler somewhere appears to be run not the GlobalExceptionHandler as I don't see the stacktrace. I would like to enter into the GlobalExceptionHandler though as I would like the errors or exceptions to be handled alike in all instances. What am I missing?

I am unable to step into the Exception handler code to see how the problem details is built and sent as response when an exception is thrown anywhere in code

public class GlobalExceptionHandler : IExceptionHandler
{
    private readonly ILogger<GlobalExceptionHandler> _logger;

    public GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger)
    {
        _logger = logger;
    }

    public async ValueTask<bool> TryHandleAsync(
        HttpContext httpContext,
        Exception exception,
        CancellationToken cancellationToken)
    {
        _logger.LogError(
            exception, "Exception occurred: {Message}", exception.Message);

        var problemDetails = new ProblemDetails
        {
            Status = StatusCodes.Status500InternalServerError,
            Title = "Server error"
        };

        httpContext.Response.StatusCode = problemDetails.Status.Value;

        await httpContext.Response
            .WriteAsJsonAsync(problemDetails, cancellationToken);

        return true;
    }
}

I have this in Program.cs. I believe I have got the placement right? Not sure why I am not able to step in. I see some fomatted exception and not the stacktrace, not sure where and how that is done.

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// Add these Lines
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
builder.Services.AddProblemDetails();


var app = builder.Build();

// Replacing this line
//app.UseExceptionHandler();
// with the following line works
  app.UseExceptionHandler("/Error");

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

For an enddpoint like ...

[HttpGet]
[Route(nameof(FileExists))]
public async Task<bool> FileExists(
    [FromQuery] string fileName, 
    [FromQuery] Guid containerId)
{

}

If fileName query parameter is not passed, the endpoint itself doesn't appear to be hit. However, some exception handler somewhere appears to be run not the GlobalExceptionHandler as I don't see the stacktrace. I would like to enter into the GlobalExceptionHandler though as I would like the errors or exceptions to be handled alike in all instances. What am I missing?

Share Improve this question edited Mar 21 at 22:11 InquisitiveLad asked Mar 21 at 1:10 InquisitiveLadInquisitiveLad 4055 silver badges18 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 3

I tried your codes and find the exception the app.UseExceptionHandler(); , it must use the path, I suggest you could use app.UseExceptionHandler("/Error"); instead.

More details, you could refer to this example:

using WebApplication9;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
}

app.UseExceptionHandler("/Error");
 app.UseHttpsRedirection();

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
{
    throw new Exception("test");
    var forecast = Enumerable.Range(1, 5).Select(index =>
        new WeatherForecast
        (
            DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
            Random.Shared.Next(-20, 55),
            summaries[Random.Shared.Next(summaries.Length)]
        ))
        .ToArray();
    return forecast;
})
.WithName("GetWeatherForecast");

app.Run();

internal record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

Result:

发布评论

评论列表(0)

  1. 暂无评论