All Projects → ofpinewood → http-exceptions

ofpinewood / http-exceptions

Licence: MIT license
Return exceptions over HTTP e.g. as ASP.NET Core Problem Details, and HTTP-specific exception classes that enable ASP.NET to generate exception information

Programming Languages

C#
18002 projects
powershell
5483 projects

Projects that are alternatives of or similar to http-exceptions

run-aspnetcore-basics retired
One Solution - One Project for web application development with Asp.Net Core & EF.Core. Only one web application project which used aspnetcore components; razor pages, middlewares, dependency injection, configuration, logging. To create websites with minimum implementation of asp.net core based on HTML5, CSS, and JavaScript. You can use this boi…
Stars: ✭ 15 (-64.29%)
Mutual labels:  aspnetcore
DNTCommon.Web.Core
DNTCommon.Web.Core provides common scenarios' solutions for ASP.NET Core 3.x applications.
Stars: ✭ 117 (+178.57%)
Mutual labels:  aspnetcore
KissLog.Sdk
KissLog is a lightweight and highly customizable logging framework for .NET applications
Stars: ✭ 33 (-21.43%)
Mutual labels:  aspnetcore
run-aspnet-identityserver4
Secure microservices with using standalone Identity Server 4 and backing with Ocelot API Gateway. Protect our ASP.NET Web MVC and API applications with using OAuth 2 and OpenID Connect in IdentityServer4. Securing your web application and API with tokens, working with claims, authentication and authorization middlewares and applying policies.
Stars: ✭ 159 (+278.57%)
Mutual labels:  aspnetcore
MonolithicArchitecture
This repository presents an approach on how to build an application using Monolithic architecture, ASP.NET Core, EntityFrameworkCore, Identity Server, CQRS, DDD
Stars: ✭ 18 (-57.14%)
Mutual labels:  aspnetcore
create-dotnet-devcert
A simple script that creates and trusts a self-signed development certificate for dotnet on Linux distributions.
Stars: ✭ 149 (+254.76%)
Mutual labels:  aspnetcore
AspNetCore.TestHost.WindowsAuth
Implements Windows authentication for ASP.NET Core TestServer-based integration test projects.
Stars: ✭ 21 (-50%)
Mutual labels:  aspnetcore
custom-exception-middleware
Middleware to catch custom or accidental exceptions
Stars: ✭ 30 (-28.57%)
Mutual labels:  exceptions
ZooKeeper-Admin
ZooKeeper 管理工具
Stars: ✭ 45 (+7.14%)
Mutual labels:  aspnetcore
smart-blazor
Blazor UI Components & Examples
Stars: ✭ 32 (-23.81%)
Mutual labels:  aspnetcore
BlazorAuthenticationSample
A sample showing some of the ASP.NET Core Blazor authentication features (also some testing...) 🚀
Stars: ✭ 78 (+85.71%)
Mutual labels:  aspnetcore
DNZ.MvcComponents
A set of useful UI-Components (HtmlHelper) for ASP.NET Core MVC based-on Popular JavaScript Plugins (Experimental project).
Stars: ✭ 25 (-40.48%)
Mutual labels:  aspnetcore
aspnet-core-react-redux-playground-template
SPA template built with ASP.NET Core 6.0 + React + Redux + TypeScript + Hot Module Replacement (HMR)
Stars: ✭ 78 (+85.71%)
Mutual labels:  aspnetcore
AspNetCore.Client
On Build client generator for asp.net core projects
Stars: ✭ 14 (-66.67%)
Mutual labels:  aspnetcore
MiCake
🍰一款基于.Net Core平台的“超轻柔“领域驱动设计(DDD)组件
Stars: ✭ 112 (+166.67%)
Mutual labels:  aspnetcore
BestForYouRecipes
Best For You recipes site in Blazor
Stars: ✭ 63 (+50%)
Mutual labels:  aspnetcore
DuckOS
Such OS; Very Duck!
Stars: ✭ 16 (-61.9%)
Mutual labels:  exceptions
mwe-cpp-exception
Minimum working example of proper C++11 exception handling
Stars: ✭ 20 (-52.38%)
Mutual labels:  exceptions
ApiFramework
Everything is an (Open)API
Stars: ✭ 26 (-38.1%)
Mutual labels:  aspnetcore
aspdotnet-core-fundamentals
Persian notes for ASP.NET Core Fundamentals course (Pluralsight)
Stars: ✭ 25 (-40.48%)
Mutual labels:  aspnetcore

HttpExceptions PineBlog

Return exceptions over HTTP

Build Status NuGet Badge License: MIT

Middleware and extensions for returning exceptions over HTTP, e.g. as ASP.NET Core Problem Details. Problem Details are a machine-readable format for specifying errors in HTTP API responses based on https://tools.ietf.org/html/rfc7807. But you are not limited to returning exception results as Problem Details, but you can create your own mappers for your own custom formats.

Where can I get it?

You can install Opw.HttpExceptions.AspNetCore from the console.

> dotnet add package Opw.HttpExceptions.AspNetCore

Getting started

Add the HttpExceptions services and the middleware in the Startup.cs of your application. First add HttpExceptions using the IMvcBuilder of IMvcCoreBuilder.

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddMvc().AddHttpExceptions();
    // or services.AddMvcCore().AddHttpExceptions();
    ...
}

Then you can add the HttpExceptions middleware using the application builder. UseHttpExceptions should be the first middleware component added to the pipeline. That way the UseHttpExceptions Middleware catches any exceptions that occur in later calls. When using HttpExceptions you don't need to use UseExceptionHandler or UseDeveloperExceptionPage.

public void Configure(IApplicationBuilder app)
{
    app.UseHttpExceptions(); // this is the first middleware component added to the pipeline
    ...
}

InvalidModelStateResponseFactory API behavior

HttpExceptions overrides the default Microsoft.AspNetCore.Mvc.ApiBehaviorOptions.InvalidModelStateResponseFactory and related settings and will use the configured ExceptionMappers.

Configuring options

You can extend or override the default behavior through the configuration options, HttpExceptionsOptions.

Include exception details

Whether or not to include the full exception details in the response. The default behavior is only to include exception details in a development environment.

mvcBuilder.AddHttpExceptions(options =>
{
    // This is the same as the default behavior; only include exception details in a development environment.
    options.IncludeExceptionDetails = context => context.RequestServices.GetRequiredService<IHostingEnvironment>().IsDevelopment();
});

Include extra properties on custom exceptions in the exception details

You can include extra public exception properties in exception details, by adding the ProblemDetailsAttribute to them.

mvcBuilder.AddHttpExceptions(options =>
{
    // The default is also true.
    options.IsProblemDetailsAttributeEnabled = true;
});

public class CustomHttpException : HttpException
{
    [ProblemDetails]
    public string PropertyA { get; set; }

    [ProblemDetails]
    public int PropertyB { get; set; }

    public long PropertyC { get; set; }
}

Is exception response

Is the response an exception and should it be handled by the HttpExceptions middleware.

mvcBuilder.AddHttpExceptions(options =>
{
    // This is a simplified version of the default behavior; only map exceptions for 4xx and 5xx responses.
    options.IsExceptionResponse = context => (context.Response.StatusCode >= 400 && context.Response.StatusCode < 600);
});

Should log exceptions (ILogger)

Should an exception be logged by the HttpExceptions middleware or not, default behavior is to log all exceptions (all status codes).

mvcBuilder.AddHttpExceptions(options =>
{
    // Only log the when it has a status code of 500 or higher, or when it is not a HttpException.
    options.ShouldLogException = exception => {
        if ((exception is HttpExceptionBase httpException && (int)httpException.StatusCode >= 500) || !(exception is HttpExceptionBase))
            return true;
        return false;
    };
});

ProblemDetails property mappings

You can inject your own mappings for the ProblemDetails properties using functions on the HttpExceptionsOptions, or by creating your own IExceptionMapper and/or IHttpResponseMapper. If you inject your own function that will be tried first, and if no result is returned the defaults will be used.

In the following example we will create a custom function mapping the ProblemDetails.Type property. By default the ProblemDetails.Type property will be set by:

  1. Either the Exception.HelpLink or the HTTP status code information link.
  2. Or the DefaultHelpLink will be used.
  3. Or an URI with the HTTP status name ("error:[status:slug]") will be used.

When the ExceptionTypeMapping or HttpContextTypeMapping are set the result of those functions will be tried first, if no result is returned the defaults will be used.

mvcBuilder.AddHttpExceptions(options =>
{
    ExceptionTypeMapping = exception => {
        // This is a example, you can implement your own logic here.
        return "My Exception Type Mapping";
    },
    HttpContextTypeMapping = context => {
        // This is a example, you can implement your own logic here.
        return "My  HttpContext Type Mapping";
    }
});

Custom ExceptionMappers

Set the ExceptionMapper collection that will be used during mapping. You can override and/or add ExceptionMappers for specific exception types. The ExceptionMappers are called in order so make sure you add them in the right order.

By default there is one ExceptionMapper configured, that ExceptionMapper catches all exceptions.

mvcBuilder.AddHttpExceptions(options =>
{
    // Override and or add ExceptionMapper for specific exception types, the default ExceptionMapper catches all exceptions.
    options.ExceptionMapper<BadRequestException, BadRequestExceptionMapper>();
    options.ExceptionMapper<ArgumentException, ExceptionMapper<ArgumentException>>();
    // The last ExceptionMapper should be a catch all, for type Exception.
    options.ExceptionMapper<Exception, MyCustomExceptionMapper>();
});

Serialization helper methods

Serialize the HTTP content to ProblemDetails.

ProblemDetails problemDetails = ((HttpContent)response.Content).ReadAsProblemDetails();

Try to get the exception details from the ProblemDetails.

SerializableException exception;
((ProblemDetails)problemDetails).TryGetExceptionDetails(out exception);

Try to get the errors dictionary from the ProblemDetails.

var IDictionary<string, object[]> errors;
((ProblemDetails)problemDetails).TryGetErrors(out errors);

Sample project using HttpExceptions middleware

See the samples/Opw.HttpExceptions.AspNetCore.Sample project for a sample implementation. This project contains examples on how to use the HttpExceptions middleware.

Please see the code 🤓

HttpExceptions

Build Status NuGet Badge License: MIT

HTTP-specific exception classes that enable ASP.NET to generate exception information. These classes can be used by themselves or as base classes for your own HttpExceptions.

Where can I get it?

You can install Opw.HttpExceptions from the console.

> dotnet add package Opw.HttpExceptions

HttpExceptions

4xx

  • 400 BadRequestException
  • 400 InvalidModelException
  • 400 ValidationErrorException<T>
  • 401 UnauthorizedException
  • 402 PaymentRequiredException
  • 403 ForbiddenException
  • 404 NotFoundException
  • 404 NotFoundException<T>
  • 409 ConflictException
  • 415 UnsupportedMediaTypeException

5xx

  • 500 HttpException (default exception with status code 500)
  • 503 ServiceUnavailableException

More exceptions

The above exception are just a few of the most common exceptions, you can create your own HttpExceptions by inheriting from the HttpExceptionBase class. For instance to create a NotAcceptableException (406).

public class NotAcceptableException : HttpExceptionBase
{
    public override HttpStatusCode StatusCode { get; protected set; } = HttpStatusCode.NotAcceptable;

    public override string HelpLink { get; set; } = ResponseStatusCodeLink.NotAcceptable;

    public NotAcceptableException(string message) : base(message) { }
}

throw new new NotAcceptableException("Totally unacceptable!");

Contributing

We accept fixes and features! Here are some resources to help you get started on how to contribute code or new content.


Copyright © 2021, Of Pine Wood. Created by Peter van den Hout. Released under the terms of the MIT license.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].