Pass an exception to the default ASP.Net CORE error handler

I’m using ASP.NET CORE 3.1 project in the new release of VS Community 2019

In the Configure(IApplicationBuilder app, IWebHostEnvironment env) in my startup.cs file I have the line:

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

So when I throw an error somewhere in a Controller e.g.

throw new Exception("User Not Found!");

This then bounces to this default IActionResult in the HomeController:

[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
    return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}

I was hoping to pass something (either the Exception or its message) to the IActionResult Error() but I’m not sure that’s possible.

So then I thought

is the Exception thrown in the BaseController accessible from the Error IActionResult at all? Possibly by using the HttpContext or the Activity ?

I can’t seem to find anything using the intellisense, not sure I’m approaching it the right way and probably need to setup a whole new error handling system.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Maybe you should add ErrorHandlingMiddleware

app.UseMiddleware<ErrorHandlingMiddleware>();

public class ErrorHandlingMiddleware
{
    private readonly RequestDelegate next;

    private readonly ILogger _logger;
    public ErrorHandlingMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
    {
        this.next = next; 
        _logger = loggerFactory.CreateLogger<ErrorHandlingMiddleware>();
    }

    public async Task Invoke(HttpContext context /* other dependencies */)
    {
        try
        {
            await next(context);
        }
        catch (Exception ex)
        {
            await HandleExceptionAsync(context, ex);
        }
    }

    private static Task HandleExceptionAsync(HttpContext context, Exception ex)
    {
        var code = HttpStatusCode.InternalServerError; // 500 if unexpected

        if (ex is AuthenticationException)
        {
            code = HttpStatusCode.Unauthorized;
        }
        var result = JsonConvert.SerializeObject(new
        {
            Status = "Error",
            ErrorCode = (int)code,
            ErrorMessage = ex.Message,
        });
        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)code;
        return context.Response.WriteAsync(result);
    }
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x