GlobalExceptionHandler 2.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package GlobalExceptionHandler --version 2.0.0
NuGet\Install-Package GlobalExceptionHandler -Version 2.0.0
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="GlobalExceptionHandler" Version="2.0.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add GlobalExceptionHandler --version 2.0.0
#r "nuget: GlobalExceptionHandler, 2.0.0"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install GlobalExceptionHandler as a Cake Addin
#addin nuget:?package=GlobalExceptionHandler&version=2.0.0

// Install GlobalExceptionHandler as a Cake Tool
#tool nuget:?package=GlobalExceptionHandler&version=2.0.0

Global Exception Handling for ASP.NET Core

Build status

GlobalExceptionHandlerDotNet allows you to configure exception handling as a convention with your ASP.NET Core application pipeline as opposed to explicitly handling them within each controller action. This could be particularly helpful in the following circumstances:

  • Reduce boiler plate try-catch logic in your controllers
  • Catch and appropriately handle exceptions outside of the ASP.NET Core framework
  • You don't want error codes being visible by consuming APIs (return 500 for every exception)

This middleware targets the ASP.NET Core pipeline with an optional dependency on the MVC framework for content negotiation if so desired.

Installation

GlobalExceptionHandler is available on NuGet and can be installed via the below commands depending on your platform:

$ Install-Package GlobalExceptionHandler

or via the .NET Core CLI:

$ dotnet add package GlobalExceptionHandler

Bare Bones Setup

// Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseExceptionHandler().WithConventions(x => {
        x.ContentType = "application/json";
        x.MessageFormatter(s => JsonConvert.SerializeObject(new
        {
            Message = "An error occured whilst processing your request"
        }));
    });
    
    app.Map("/error", x => x.Run(y => throw new Exception()));
}

Any exception thrown by your application will result in the follow response:

HTTP/1.1 500 Internal Server Error
Date: Fri, 24 Nov 2017 09:17:05 GMT
Content-Type: application/json
Server: Kestrel
Cache-Control: no-cache
Pragma: no-cache
Transfer-Encoding: chunked
Expires: -1

{
  "Message": "An error occured whilst processing your request"
}

Handling specific exceptions

You can explicitly handle exceptions like so:

app.UseExceptionHandler().WithConventions(x => {
    x.ContentType = "application/json";
    x.MessageFormatter(s => JsonConvert.SerializeObject(new
    {
        Message = "An error occured whilst processing your request"
    }));

    x.ForException<RecordNotFoundException>().ReturnStatusCode(HttpStatusCode.NotFound);
});
HTTP/1.1 404 Not Found
Date: Sat, 25 Nov 2017 01:47:51 GMT
Content-Type: application/json
Server: Kestrel
Cache-Control: no-cache
Pragma: no-cache
Transfer-Encoding: chunked
Expires: -1

{
  "Message": "An error occured whilst processing your request"
}

Per exception responses

Or provide a custom error response for the exception type thrown:

app.UseExceptionHandler().WithConventions(x => {
    x.ContentType = "application/json";
    x.MessageFormatter(s => JsonSerializer(new
    {
        Message = "An error occured whilst processing your request"
    }));

    x.ForException<RecordNotFoundException>().ReturnStatusCode(HttpStatusCode.NotFound)
        .UsingMessageFormatter((ex, context) => JsonSerializer(new {
            Message = "Record could not be found"
        }));
});

Response:

HTTP/1.1 404 Not Found
...
{
  "Message": "Record could not be found"
}

Alternatively you could output the exception content if you prefer:

app.UseExceptionHandler().WithConventions(x => {
    x.ContentType = "application/json";
    x.MessageFormatter(s => JsonSerializer(new
    {
        Message = "An error occured whilst processing your request"
    }));

    x.ForException<RecordNotFoundException>().ReturnStatusCode(HttpStatusCode.NotFound)
        .UsingMessageFormatter((ex, context) => JsonSerializer(new {
            Message = ex.Message
        }));
});

Content Negotiation

GlobalExceptionHandlerDotNet plugs into the .NET Core pipeline, meaning you can also take advantage of content negotiation provided by the ASP.NET Core MVC framework, enabling the clients to didcate the preferred content type.

To enable content negotiation against ASP.NET Core MVC you will need to include the GlobalExceptionHandler.ContentNegotiation.Mvc package.

Logging

Under most circumstances you'll want to keep a log of any exceptions thrown in your log aggregator of choice. You can do this via the OnError endpoint:

x.OnError((exception, httpContext) =>
{
    _logger.Error(exception.Message);
    return Task.CompletedTask;
});

Configuration Options:

  • ContentType
    Specify the returned content type (default is application/json).

  • MessageFormatter(...)
    Set a default message formatter that any unhandled exception will trigger.

x.MessageFormatter((ex, context) => {
    return "Oops, something went wrong! Check the logs for more information.";
});
  • DebugMode Enabling debug mode will cause GlobalExceptionHandlerDotNet to return the full exception thrown. This is disabled by default and should not be set in production.
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (7)

Showing the top 5 NuGet packages that depend on GlobalExceptionHandler:

Package Downloads
GlobalExceptionHandler.ContentNegotiation.Mvc

Enable content negotiation for GlobalExceptionHandlerDotNet when using ASP.NET Core MVC

DiegoRangel.DotNet.Framework.CQRS.API

A common library for implementing CQRS based Api layer.

Prospa.Extensions.AspNetCore.Mvc.Core

ASP.NET Core MVC core components extensions.

Harpy.Presentation

Basis for the presentation layer of the Harpy Framework

Packs.Template.BaseApi

Basis for any Packs API

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
4.0.2 1,659,581 3/15/2019
4.0.1 3,871 2/26/2019
4.0.0 239,772 10/27/2018
4.0.0-beta2 9,211 9/20/2018
4.0.0-beta1 1,785 9/18/2018
3.0.0 66,387 12/20/2017
2.0.0 8,792 11/27/2017
1.0.3 4,913 10/9/2017
1.0.2 1,779 9/14/2017
1.0.1 1,604 9/14/2017
1.0.0 1,749 9/14/2017
1.0.0-beta 1,436 9/13/2017