2

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.

1
  • 1
    You can use action filters. For more details refer to this Error Handling Commented Nov 26, 2020 at 12:17

1 Answer 1

2

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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, I had no idea Middleware was so easy to implement. When I search handling errors in asp.net core it seems there are some very convoluted ways to do things. This is great. Direct and easy to swallow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.