All Projects → isaacnborges → custom-exception-middleware

isaacnborges / custom-exception-middleware

Licence: MIT license
Middleware to catch custom or accidental exceptions

Programming Languages

C#
18002 projects

Projects that are alternatives of or similar to custom-exception-middleware

Bugsnag Go
Automatic panic monitoring for Go and Go web frameworks, like negroni, gin, and revel
Stars: ✭ 155 (+416.67%)
Mutual labels:  error-handling, error, exceptions
Ben.demystifier
High performance understanding for stack traces (Make error logs more productive)
Stars: ✭ 2,142 (+7040%)
Mutual labels:  error-handling, exceptions, error-messages
Bugsnag Node
[DEPRECATED] Please upgrade to our Universal JS notifier "@bugsnag/js" • https://github.com/bugsnag/bugsnag-js
Stars: ✭ 48 (+60%)
Mutual labels:  error-handling, error, exceptions
Swift Error Handler
Error handling library for Swift
Stars: ✭ 172 (+473.33%)
Mutual labels:  error-handling, error
Bugsnag Cocoa
Bugsnag crash reporting for iOS, macOS and tvOS apps
Stars: ✭ 167 (+456.67%)
Mutual labels:  error-handling, exceptions
Pyrollbar
Error tracking and logging from Python to Rollbar
Stars: ✭ 169 (+463.33%)
Mutual labels:  error-handling, exceptions
Go Errortree
Go library for handling errors organized as a tree
Stars: ✭ 59 (+96.67%)
Mutual labels:  error-handling, error
Emperror
The Emperor takes care of all errors personally
Stars: ✭ 201 (+570%)
Mutual labels:  error-handling, error
Failure
failure is a utility package for handling application errors.
Stars: ✭ 187 (+523.33%)
Mutual labels:  error-handling, error
Bugsnag Ruby
Bugsnag error monitoring & reporting software for rails, sinatra, rack and ruby
Stars: ✭ 211 (+603.33%)
Mutual labels:  error-handling, exceptions
bugsnag-java
Bugsnag error reporting for Java.
Stars: ✭ 51 (+70%)
Mutual labels:  error-handling, exceptions
Error Message
📋 Error message component
Stars: ✭ 129 (+330%)
Mutual labels:  message, error-handling
telegram-logger-errors
Telegram logger errors package laravel | Laravel пакет telegram логгер ошибок
Stars: ✭ 15 (-50%)
Mutual labels:  message, error-messages
Graphql Errors
Simple error handler for GraphQL Ruby ❗️
Stars: ✭ 170 (+466.67%)
Mutual labels:  error-handling, error
Extensible Custom Error
JavaScript extensible custom error that can take a message and/or an Error object
Stars: ✭ 64 (+113.33%)
Mutual labels:  error-handling, error
Exceptions4c
🐑 An exception handling framework for C
Stars: ✭ 189 (+530%)
Mutual labels:  error-handling, exceptions
Bugsnag Android Ndk
DEPRECATED - this project now lives at bugsnag/bugsnag-android
Stars: ✭ 42 (+40%)
Mutual labels:  error-handling, exceptions
koa-better-error-handler
A better error-handler for Lad and Koa. Makes `ctx.throw` awesome (best used with koa-404-handler)
Stars: ✭ 51 (+70%)
Mutual labels:  error-handling, error
Human Signals
Human-friendly process signals
Stars: ✭ 223 (+643.33%)
Mutual labels:  error-handling, error
TrackJS-Node
TrackJS Error Monitoring agent for NodeJS
Stars: ✭ 26 (-13.33%)
Mutual labels:  error-handling, error

Custom Exception Middleware

Github actions status Quality Gate Status Nuget version Nuget downloads

It is a middleware for error handling in ASP.NET projects, the application aims to facilitate and handle when an accidental or custom exception occurs in the project.

Install

  • Package Manager Console

Install-Package CustomExceptionMiddleware
  • .Net CLI

dotnet add package CustomExceptionMiddleware

Minimum requirements to use: .NET Standard 2.0

Compilation requirements: .NET 6

How to use

It's very simple to use, go to Startup.cs on Configure() method and add this code:

app.UseCustomExceptionMiddleware();

Example output

{
    "type": "VALIDATION_ERRORS",
    "error": {
        "msg": "Custom domain exception message"
    }
}

Custom use

  • Create object options
    It's possible create a CustomExceptionOptions to customize the return middleware object, to view the StackTrace like this:

    app.UseCustomExceptionMiddleware(new CustomExceptionOptions
    {
        ViewStackTrace = true
    });
  • Use an action options
    Other options to customize the return object is using an action to create a CustomErrorModel

    app.UseCustomExceptionMiddleware(options =>
    {
        options.ViewStackTrace = true;
    });

In both cases the output will include de stack trace in detail object property:

Example output

{
    "type": "VALIDATION_ERRORS",
    "error": {
        "msg": "Custom domain exception message",
        "detail": "at CustomExceptionMiddleware.WebAppTest.Custom.ProductService.GetDomainException(Boolean returnProducts) in C:\\isaacnborges\\projects\\custom-exception-middleware\\tests\\CustomExceptionMiddleware.WebAppTest.Custom\\ProductService.cs:line 18\r\n   at CustomExceptionMiddleware.WebAppTest.Custom.Controllers.ProductController.GetDomain(Boolean returnProduct) in C:\\isaacnborges\\projects\\custom-exception-middleware\\tests\\CustomExceptionMiddleware.WebAppTest.Custom\\Controllers\\ProductController.cs:line 26"
    }
}

Configure Exceptions

This middleware use some custom exceptions to catch and personalize the response status code.

The custom middleware supports the following Exceptions:

Exception Status code description Status code
DomainException BadRequest 400
UnauthorizedException Unauthorized 401
CannotAccessException Forbidden 403
NotFoundException NotFound 404
Exception InternalServerError 500

DomainException is an abstract exception, so to use it's necessary create other exception and inherit. The others exceptions only throw an exception

Custom exception example

public class InvalidStateException : DomainException
{
        public InvalidStateException()
        { }

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

        public InvalidStateException(string message, Exception innerException) : base(message, innerException)
        { }
}

Throw exceptions

throw new InvalidStateException("Custom domain exception message");
throw new UnauthorizedException("Custom unauthorized exception message");
throw new CannotAccessException("Custom cannot access exception message");
throw new NotFoundException("Custom not found exception message");
throw new Exception("Custom exception message");

Customize exception type

It's possible to customize the exception type when throw an exception, just pass the type in an exception constructor.

throw new CustomDomainException("Custom domain exception message", "OTHER_CUSTOM_TYPE");

Samples

Inside the samples folder has two projects that could be used for test the and validate the middleware.

Run the sample projects

  • WebAppTest
    dotnet run --project .\samples\CustomExceptionMiddleware.WebAppTest\
    
  • WebAppTest.Custom
    dotnet run --project .\samples\CustomExceptionMiddleware.WebAppTest.Custom\
    

Samples documentation

Logging

This middleware will Log some informations that can be used for monitoring and observability, like TraceIdentifier, request and exception informations like message type and stack trace:

Example log:

Occurred an exception - TraceId: 0HMBO9LGH0JHD:00000002 - ExceptionType: InvalidStateException - Message: Custom domain exception message
CustomExceptionMiddleware.WebAppTest.InvalidStateException: Custom domain exception message
at CustomExceptionMiddleware.WebAppTest.Custom.ProductService.GetDomainException(Boolean returnProducts) in C:\\isaacnborges\\projects\\custom-exception-middleware\\tests\\CustomExceptionMiddleware.WebAppTest.Custom\\ProductService.cs:line 18\r\n   at CustomExceptionMiddleware.WebAppTest.Custom.Controllers.ProductController.GetDomain(Boolean returnProduct) in C:\\isaacnborges\\projects\\custom-exception-middleware\\tests\\CustomExceptionMiddleware.WebAppTest.Custom\\Controllers\\ProductController.cs:line 26

Using custom attribute

In some scenarios the project needs other response object, integrations with 3rd party systems for example, this middleware contains an attribute that could be ignore, it's possible use in class or methods

Using the IgnoreCustomExceptionAttribute attribute the middleware will ignore your own flow. To use it simply, decorate the class or method with the name.

  • Class example

    [IgnoreCustomException]
    public class ValuesController : ControllerBase
    {
        [HttpGet]
        public IActionResult Get()
        {
            throw new CustomDomainException("Some error ignore class");
        }
  • Method example

    [IgnoreCustomException]
    [HttpGet("ignore")]
    public IActionResult GetIgnore()
    {
        throw new CustomDomainException("Some error ignore method");
    }

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

License

MIT

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].