16

I am looking for a way to return the details of any exception that occur when calling a method of my web API.

By default in production environment, error 500 "Internal Server Error" is the only information returned by the API.

It is a private API that is not published over the internet, and the caller application needs to get and store all details in case of exception.

The exception details could be JSON formatted in the HttpResponse content, allowing the caller to read the Message attribute, and the StackTraceString attribute of the exception (No HTTP page like UseDeveloperExceptionPage configuration).

Currently the default Startup Configure method is:

public class Startup
{   
    [...]

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, Microsoft.Extensions.Logging.ILoggerFactory loggerFactory)
    {
        loggerFactory.AddNLog();
        env.ConfigureNLog(Path.Combine(AppContext.BaseDirectory, "nlog.config"));

        if ( env.IsDevelopment() )
            app.UseDeveloperExceptionPage();
        else
            app.UseStatusCodePages();

        app.UseMvc();
    }
}

3 Answers 3

24

You could write a custom middleware, which intercepts all exceptions and returns them to the caller:

public class ExceptionHandler
{
    private readonly RequestDelegate _next;

    public ExceptionHandler(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next.Invoke(context);
        }
        catch (Exception ex)
        {
            await HandleExceptionAsync(context, ex);
        }
    }

    private async Task HandleExceptionAsync(HttpContext context, Exception exception)
    {
        var response = context.Response;
        response.ContentType = "application/json";
        response.StatusCode = (int)HttpStatusCode.InternalServerError;
        await response.WriteAsync(JsonConvert.SerializeObject(new
        {
            // customize as you need
            error = new
            {
                message = exception.Message,
                exception = exception.GetType().Name
            }
        }));
    }
}

and register it in your Startup Configure method:

if (env.IsDevelopment())
    app.UseDeveloperExceptionPage();
else
   app.UseMiddleware<ExceptionHandler>();
4
  • It works perfectly, +1. We should have that kind of example in learn.microsoft.com/en-us/aspnet/core/fundamentals/… Feb 5, 2018 at 15:57
  • @CommonGuy - where would you store this class? Do you put it in a Models directory or what is the recommended practice?
    – JonH
    Jan 30, 2019 at 4:04
  • Depends on how you structure your project. I personally have folders for each layer (Controller, Repository, ...), so I put this class in a Middleware folder Jan 30, 2019 at 6:57
  • 1
    @CommonGuy - So you've got a folder called "Middleware" with this in it - seems reasonable. I do have a folder for each layer, controller, repository, service, but I did not have a Middleware folder.
    – JonH
    Jan 30, 2019 at 14:53
9

Alternatively to middleware, you can create ActionFilterAttribute and change IActionResult

Here is simple example attribuet that for all unhandled exceptions returns 400 Bad request with Exception method.

public class MyUnhandledExceptionFilter : ActionFilterAttribute, IExceptionFilter
{        
    public void OnException(ExceptionContext context)
    {           
        context.Result = new BadRequestObjectResult(context.Exception.Message);
    }
}

You then register it in startup's ConfigureServices method like this

services.AddMvc(options =>
        {
            options.Filters.Add(typeof(MyUnhandledExceptionFilter));
        })

This only catches exceptions that reached MVC, which in most cases is what you need

2
1

Remember to add it before UseMvc (or UseRouting in .Net Core 3) as order is important!!!!!

        app.UseRouting ();
        app.UseMiddleware (typeof (ErrorHandlingMiddleware));

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.