{"id":37050301,"url":"https://github.com/isaacnborges/custom-exception-middleware","last_synced_at":"2026-01-14T05:50:05.956Z","repository":{"id":39586413,"uuid":"403637809","full_name":"isaacnborges/custom-exception-middleware","owner":"isaacnborges","description":"Middleware to catch custom or accidental exceptions","archived":false,"fork":false,"pushed_at":"2023-12-21T20:04:22.000Z","size":102,"stargazers_count":52,"open_issues_count":0,"forks_count":1,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-11-21T10:15:29.013Z","etag":null,"topics":["custom-exceptions","error","error-handling","error-messages","exceptions","message","middleware"],"latest_commit_sha":null,"homepage":"https://bit.ly/3C1aZzs","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/isaacnborges.png","metadata":{"files":{"readme":"README-nuget.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2021-09-06T13:43:43.000Z","updated_at":"2025-07-07T13:00:02.000Z","dependencies_parsed_at":"2023-01-29T15:45:17.160Z","dependency_job_id":null,"html_url":"https://github.com/isaacnborges/custom-exception-middleware","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"purl":"pkg:github/isaacnborges/custom-exception-middleware","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/isaacnborges%2Fcustom-exception-middleware","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/isaacnborges%2Fcustom-exception-middleware/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/isaacnborges%2Fcustom-exception-middleware/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/isaacnborges%2Fcustom-exception-middleware/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/isaacnborges","download_url":"https://codeload.github.com/isaacnborges/custom-exception-middleware/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/isaacnborges%2Fcustom-exception-middleware/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28411574,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-14T05:26:33.345Z","status":"ssl_error","status_checked_at":"2026-01-14T05:21:57.251Z","response_time":107,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["custom-exceptions","error","error-handling","error-messages","exceptions","message","middleware"],"created_at":"2026-01-14T05:50:05.196Z","updated_at":"2026-01-14T05:50:05.950Z","avatar_url":"https://github.com/isaacnborges.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Custom Exception Middleware\n\n[![Github actions status](https://github.com/isaacnborges/custom-exception-middleware/actions/workflows/dotnet-workflow.yml/badge.svg)](https://github.com/isaacnborges/custom-exception-middleware/actions/workflows/dotnet-workflow.yml)\n[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=isaacnborges_custom-exception-middleware\u0026metric=alert_status)](https://sonarcloud.io/dashboard?id=isaacnborges_custom-exception-middleware)\n[![Nuget](https://img.shields.io/nuget/v/CustomExceptionMiddleware?label=Nuget\u0026style=flat)](https://www.nuget.org/packages/CustomExceptionMiddleware/)\n\nIt is a middleware for error handling in [ASP.NET](https://dotnet.microsoft.com/apps/aspnet) projects, the application aims to facilitate and handle when an accidental or custom exception occurs in the project.\n\n## Install\n\n- ### Package Manager Console\n\n```\nInstall-Package CustomExceptionMiddleware\n```\n\n- ### .Net CLI\n\n```\ndotnet add package CustomExceptionMiddleware\n```\n\n### Minimum requirements to use: [.NET Standard 2.0](https://docs.microsoft.com/en-us/dotnet/standard/net-standard)\n\n### Compilation requirements: [.NET 8](https://dotnet.microsoft.com/download/dotnet/8.0)\n\n## How to use\n\nIt's very simple to use, go to `Startup.cs` on `Configure()` method and add this code:\n\n```c#\napp.UseCustomExceptionMiddleware();\n```\n\nOr if you are using any of the newer versions of .NET put the code after the app `build` on `Program.cs` file.\n```c#\nvar app = builder.Build();\napp.UseCustomExceptionMiddleware();\n```\n\nExample output\n```json\n{\n    \"type\": \"VALIDATION_ERRORS\",\n    \"error\": {\n        \"msg\": \"Custom domain exception message\"\n    }\n}\n```\n\n### Custom use\n- Create object options:\nIt's possible create a `CustomExceptionOptions` to customize the return middleware object, to view the `StackTrace` like this:\n\n    ```c#\n    app.UseCustomExceptionMiddleware(new CustomExceptionOptions\n    {\n        ViewStackTrace = true\n    });\n    ```\n\n- Use an action options:\nOther options to customize the return object is using an action to create a `CustomErrorModel`\n    ```c#\n    app.UseCustomExceptionMiddleware(options =\u003e\n    {\n        options.ViewStackTrace = true;\n    });\n    ```\n\nIn both cases the output will include de stack trace in `detail` object property:    \n\nExample output\n```json\n{\n    \"type\": \"VALIDATION_ERRORS\",\n    \"error\": {\n        \"msg\": \"Custom domain exception message\",\n        \"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\"\n    },\n}\n```\n\n### Configure Exceptions\nThis middleware use some custom exceptions to catch and personalize the response status code.\n\nThe custom middleware supports the following **Exceptions**:\n\n```\nException              Status code description  Status code\n---------------------  -----------------------  -----------\nDomainException        BadRequest                  400        \nUnauthorizedException  Unauthorized                401        \nCannotAccessException  Forbidden                   403        \nNotFoundException      NotFound                    404        \nException              InternalServerError         500        \n```\n\n`DomainException` is an abstract exception, so to use it's necessary create other exception and inherit. The others exceptions only throw an exception\n\n#### Custom exception example\n```c#\npublic class InvalidStateException : DomainException\n{\n        public InvalidStateException()\n        { }\n\n        public InvalidStateException(string message) : base(message)\n        { }\n\n        public InvalidStateException(string message, Exception innerException) : base(message, innerException)\n        { }\n}\n```\n\n#### Throw exceptions\n```c#\nthrow new InvalidStateException(\"Custom domain exception message\");\nthrow new UnauthorizedException(\"Custom unauthorized exception message\");\nthrow new CannotAccessException(\"Custom cannot access exception message\");\nthrow new NotFoundException(\"Custom not found exception message\");\nthrow new Exception(\"Custom exception message\");\n```\n\n#### Customize exception type\nIt's possible to customize the exception type when throw an exception, just pass the type in an exception constructor. \n```c#\nthrow new CustomDomainException(\"Custom domain exception message\", \"OTHER_CUSTOM_TYPE\");\n```\n\n### Samples\nInside the `samples` folder has two projects that could be used for test the and validate the middleware.\n\n#### Run the sample projects\n- WebAppTest\n    ```\n    dotnet run --project .\\samples\\CustomExceptionMiddleware.WebAppTest\\\n    ```\n- WebAppTest.Custom\n    ```\n    dotnet run --project .\\samples\\CustomExceptionMiddleware.WebAppTest.Custom\\\n    ```\n#### Samples documentation\n- Swagger\n    - [WebAppTest](http://localhost:5000/swagger/index.html)\n    - [WebAppTest.Custom](http://localhost:5001/swagger/index.html)\n- Postman\n    - Open `docs` folder, inside has a [postman](https://www.postman.com/) collection that could be used for test.\n\n## Logging\nThis 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:\n\nExample log:\n\n```\nOccurred an exception - TraceId: 0HMBO9LGH0JHD:00000002 - ExceptionType: InvalidStateException - Message: Custom domain exception message\nCustomExceptionMiddleware.WebAppTest.InvalidStateException: Custom domain exception message\nat 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\n```\n\n## Using custom attribute\nIn some scenarios the project needs other response object, integrations with 3rd party systems for example, this middleware contains an [attribute](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/attributes/) that could be ignore, it's possible use in class or methods\n\nUsing the `IgnoreCustomExceptionAttribute` attribute the middleware will ignore your own flow. To use it simply, decorate the class or method with the name.\n\n - Class example\n    ```c#\n    [IgnoreCustomException]\n    public class ValuesController : ControllerBase\n    {\n        [HttpGet]\n        public IActionResult Get()\n        {\n            throw new CustomDomainException(\"Some error ignore class\");\n        }\n    ```\n\n - Method example\n    ```c#\n    [IgnoreCustomException]\n    [HttpGet(\"ignore\")]\n    public IActionResult GetIgnore()\n    {\n        throw new CustomDomainException(\"Some error ignore method\");\n    }\n    ```\n\n## Contributing\nPull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.\n\nPlease make sure to update tests as appropriate.\n\n## License\n[MIT](https://opensource.org/licenses/MIT)","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fisaacnborges%2Fcustom-exception-middleware","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fisaacnborges%2Fcustom-exception-middleware","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fisaacnborges%2Fcustom-exception-middleware/lists"}