A filter and middleware that can translate exceptions into nice http resonses. This allows you to throw meaningfull exceptions from your framework, business code or other middlewares and translate the exceptions to nice and friendly http responses.
This code based on Owin Friendly Exceptions Middleware created by Anders Åberg and has been adapted for ASP.NET Core usage by Andriy S'omak.
Before using of the library Nuget Package must be installed.
Install-Package AspNetCore.FriendlyExceptions
There are a two ways of using of the library: using ExceptionFilter or registering Midlleware. You can choose any of them.
Add transformation rules to the Startup.cs file.
public void ConfigureServices(IServiceCollection services)
{
...
services.AddFriendlyExceptionsTransforms(options =>
{
options.Transforms = TransformsCollectionBuilder.Begin()
.Map<ExampleException>()
.To(HttpStatusCode.BadRequest, "This is the reasonphrase",
ex => "And this is the response content: " + ex.Message)
.Map<SomeCustomException>()
.To(HttpStatusCode.NoContent, "Bucket is emtpy", ex => string.Format("Inner details: {0}", ex.Message))
.Map<EntityUnknownException>()
.To(HttpStatusCode.NotFound, "Entity does not exist", ex => ex.Message)
.Map<InvalidAuthenticationException>()
.To(HttpStatusCode.Unauthorized, "Invalid authentication", ex => ex.Message)
.Map<AuthorizationException>()
.To(HttpStatusCode.Forbidden, "Forbidden", ex => ex.Message)
// Map all other exceptions if needed.
// Also it would be useful if you want to map exception to a known model.
.MapAllOthers()
.To(HttpStatusCode.InternalServerError, "Internal Server Error", ex => ex.Message)
.Done();
});
...
}
By default, FriendlyExceptions sets the response Content-Type to text/plain
. To use a different type:
.Map<SomeJsonException>()
.To(HttpStatusCode.BadRequest, "This exception is json",
ex => JsonConvert.SerializeObject(ex.Message), "application/json")
Register ExceptionFilter.
public void ConfigureServices(IServiceCollection services)
{
...
services.AddMvc()
.AddMvcOptions(s => s.Filters.Add(typeof(FriendlyExceptionAttribute)))
...
}
Add filter attribute to the Controller.
[Produces("application/json")]
[FriendlyException]
public class AccountController : Controller
{
...
In case you use middleware, the registration method must be at the top of list of all registrations.
public void Configure(IApplicationBuilder app)
{
app.UseFriendlyExceptions();
...
}
Contributions are welcome. Just open an Issue or submit a PR.
You can reach me via my email