├── .dockerignore ├── .editorconfig ├── .github ├── FUNDING.yml └── workflows │ ├── Publish ApiExceptions.yml │ └── Tests.yml ├── .gitignore ├── ApiExceptions.sln ├── LICENSE ├── README.md ├── sample └── BitzArt.ApiExceptions.AspNetCore.Sample │ ├── BitzArt.ApiExceptions.AspNetCore.Sample.csproj │ ├── Controllers │ ├── CustomExceptionsController.cs │ ├── InnerExceptionController.cs │ ├── PredefinedExceptionsController.cs │ └── SuccessfulRequestController.cs │ ├── Exceptions │ ├── MyCustomAnonymousPayloadException.cs │ ├── MyCustomApiException.cs │ └── MyCustomPayloadApiException.cs │ ├── Program.cs │ ├── Properties │ └── launchSettings.json │ ├── appsettings.json │ └── requests.http ├── src ├── BitzArt.ApiExceptions.AspNetCore │ ├── Attributes │ │ └── ApiExceptionFilterAttribute.cs │ ├── BitzArt.ApiExceptions.AspNetCore.csproj │ ├── Config.cs │ ├── Extensions │ │ ├── AddApiExceptionHandlerExtension.cs │ │ ├── ApiExceptionExtensions.cs │ │ ├── ExceptionExtensions.cs │ │ └── UseApiExceptionHandlerExtension.cs │ ├── Handlers │ │ └── ApiExceptionHandler.cs │ ├── Middleware │ │ └── ApiExceptionHandlingMiddleware.cs │ └── Models │ │ ├── ApiExceptionHandlerOptions.cs │ │ └── ProblemDetails.cs ├── BitzArt.ApiExceptions.OpenTelemetry │ ├── BitzArt.ApiExceptions.OpenTelemetry.csproj │ └── ExceptionTelemetry.cs └── BitzArt.ApiExceptions │ ├── ApiException.cs │ ├── BitzArt.ApiExceptions.csproj │ ├── Enum │ └── ApiStatusCode.cs │ ├── Extensions │ └── ObjectParsingExtensions.cs │ ├── Interface │ └── IApiExceptionHandler.cs │ └── Models │ ├── ApiExceptionBase.cs │ ├── ApiExceptionPayload.cs │ └── PredefinedExceptions.cs └── tests ├── BitzArt.ApiExceptions.AspNetCore.Tests ├── BitzArt.ApiExceptions.AspNetCore.Tests.csproj └── ProblemDetailsTests.cs ├── BitzArt.ApiExceptions.OpenTelemetry.Tests ├── BitzArt.ApiExceptions.OpenTelemetry.Tests.csproj └── Tests.cs └── BitzArt.ApiExceptions.Tests ├── ApiExceptionBaseTests.cs ├── ApiExceptionPayloadTests.cs └── BitzArt.ApiExceptions.Tests.csproj /.dockerignore: -------------------------------------------------------------------------------- 1 | **/.classpath 2 | **/.dockerignore 3 | **/.env 4 | **/.git 5 | **/.gitignore 6 | **/.project 7 | **/.settings 8 | **/.toolstarget 9 | **/.vs 10 | **/.vscode 11 | **/*.*proj.user 12 | **/*.dbmdl 13 | **/*.jfm 14 | **/azds.yaml 15 | **/bin 16 | **/charts 17 | **/docker-compose* 18 | **/Dockerfile* 19 | **/node_modules 20 | **/npm-debug.log 21 | **/obj 22 | **/secrets.dev.yaml 23 | **/values.dev.yaml 24 | LICENSE 25 | README.md -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | [*.{cs,vb}] 2 | 3 | # IDE0028: Simplify collection initialization 4 | dotnet_diagnostic.IDE0028.severity = silent 5 | 6 | # IDE0290: Use primary constructor 7 | dotnet_diagnostic.IDE0290.severity = silent 8 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | custom: ['https://paypal.me/BitzArtDev'] 2 | -------------------------------------------------------------------------------- /.github/workflows/Publish ApiExceptions.yml: -------------------------------------------------------------------------------- 1 | name: Release ApiExceptions 2 | 3 | on: 4 | repository_dispatch: 5 | push: 6 | tags: 7 | - "ApiExceptions-v[0-9]+.[0-9]+.[0-9]+*" 8 | 9 | env: 10 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 11 | NUGET_APIKEY: ${{ secrets.NUGET_APIKEY}} 12 | 13 | jobs: 14 | 15 | ApiExceptions: 16 | name: ApiExceptions 17 | runs-on: ubuntu-latest 18 | steps: 19 | 20 | - name: Checkout 21 | uses: actions/checkout@v2 22 | 23 | - name: Verify commit 24 | run: | 25 | git fetch --no-tags --prune --depth=1 origin +refs/heads/*:refs/remotes/origin/* 26 | git branch --remote --contains | grep origin/main 27 | 28 | - name: Set version 29 | run: echo "VERSION=${GITHUB_REF/refs\/tags\/ApiExceptions-v/}" >> $GITHUB_ENV 30 | 31 | - name: Build 32 | run: | 33 | dotnet build ApiExceptions.sln --configuration Release /p:Version=${VERSION} 34 | dotnet pack ApiExceptions.sln --configuration Release /p:Version=${VERSION} --no-build --output . 35 | 36 | - name: Push 37 | run: | 38 | dotnet nuget push BitzArt.ApiExceptions.${VERSION}.nupkg --source https://api.nuget.org/v3/index.json --api-key ${NUGET_APIKEY} 39 | dotnet nuget push BitzArt.ApiExceptions.AspNetCore.${VERSION}.nupkg --source https://api.nuget.org/v3/index.json --api-key ${NUGET_APIKEY} 40 | dotnet nuget push BitzArt.ApiExceptions.OpenTelemetry.${VERSION}.nupkg --source https://api.nuget.org/v3/index.json --api-key ${NUGET_APIKEY} 41 | -------------------------------------------------------------------------------- /.github/workflows/Tests.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | tags-ignore: 8 | - '*' 9 | 10 | jobs: 11 | tests: 12 | 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - uses: actions/checkout@v2 17 | 18 | - name: Install dependencies 19 | run: dotnet restore 20 | 21 | - name: Build 22 | run: dotnet build --configuration Release --no-restore 23 | 24 | - name: Test 25 | run: dotnet test --no-restore --verbosity normal -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /ApiExceptions.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.2.32516.85 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{615B001B-EF7F-4F09-B2CB-383F169E4627}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BitzArt.ApiExceptions.AspNetCore", "src\BitzArt.ApiExceptions.AspNetCore\BitzArt.ApiExceptions.AspNetCore.csproj", "{1BBD5146-9B5E-4DF8-BFB5-5B931B7E3183}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "sample", "sample", "{8F84E1A4-E5B4-4FE5-8200-E5AF0ACCE41C}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BitzArt.ApiExceptions.AspNetCore.Sample", "sample\BitzArt.ApiExceptions.AspNetCore.Sample\BitzArt.ApiExceptions.AspNetCore.Sample.csproj", "{B2E29FB2-B157-4316-A38E-C99D242AE1A9}" 13 | EndProject 14 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".github", ".github", "{AA1D9106-BE0A-4171-AEC4-4BB6AA566DB7}" 15 | EndProject 16 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "workflows", "workflows", "{C926A148-2053-4836-B8AA-D9548C35BDC9}" 17 | ProjectSection(SolutionItems) = preProject 18 | .github\workflows\Publish ApiExceptions.yml = .github\workflows\Publish ApiExceptions.yml 19 | .github\workflows\Tests.yml = .github\workflows\Tests.yml 20 | EndProjectSection 21 | EndProject 22 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BitzArt.ApiExceptions", "src\BitzArt.ApiExceptions\BitzArt.ApiExceptions.csproj", "{DC2B54EB-5BF8-406A-8C1A-E49508BA7BAC}" 23 | EndProject 24 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{633F6437-E58A-420F-AE01-7FDC6B7E2CA3}" 25 | EndProject 26 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BitzArt.ApiExceptions.Tests", "tests\BitzArt.ApiExceptions.Tests\BitzArt.ApiExceptions.Tests.csproj", "{D9311895-F541-4816-BD05-1DF39C86A01B}" 27 | EndProject 28 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BitzArt.ApiExceptions.AspNetCore.Tests", "tests\BitzArt.ApiExceptions.AspNetCore.Tests\BitzArt.ApiExceptions.AspNetCore.Tests.csproj", "{BF689FDE-D5BE-4852-A16A-066EDE5E71B8}" 29 | EndProject 30 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BitzArt.ApiExceptions.OpenTelemetry", "src\BitzArt.ApiExceptions.OpenTelemetry\BitzArt.ApiExceptions.OpenTelemetry.csproj", "{F431B580-4D6A-4658-8256-4F7AEE0AA03C}" 31 | EndProject 32 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BitzArt.ApiExceptions.OpenTelemetry.Tests", "tests\BitzArt.ApiExceptions.OpenTelemetry.Tests\BitzArt.ApiExceptions.OpenTelemetry.Tests.csproj", "{81ED4DC9-5854-432F-9723-72372189FB9D}" 33 | EndProject 34 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{A41345A8-0644-4185-9006-14938AE0F321}" 35 | ProjectSection(SolutionItems) = preProject 36 | .editorconfig = .editorconfig 37 | EndProjectSection 38 | EndProject 39 | Global 40 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 41 | Debug|Any CPU = Debug|Any CPU 42 | Release|Any CPU = Release|Any CPU 43 | EndGlobalSection 44 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 45 | {1BBD5146-9B5E-4DF8-BFB5-5B931B7E3183}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 46 | {1BBD5146-9B5E-4DF8-BFB5-5B931B7E3183}.Debug|Any CPU.Build.0 = Debug|Any CPU 47 | {1BBD5146-9B5E-4DF8-BFB5-5B931B7E3183}.Release|Any CPU.ActiveCfg = Release|Any CPU 48 | {1BBD5146-9B5E-4DF8-BFB5-5B931B7E3183}.Release|Any CPU.Build.0 = Release|Any CPU 49 | {B2E29FB2-B157-4316-A38E-C99D242AE1A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 50 | {B2E29FB2-B157-4316-A38E-C99D242AE1A9}.Debug|Any CPU.Build.0 = Debug|Any CPU 51 | {B2E29FB2-B157-4316-A38E-C99D242AE1A9}.Release|Any CPU.ActiveCfg = Release|Any CPU 52 | {B2E29FB2-B157-4316-A38E-C99D242AE1A9}.Release|Any CPU.Build.0 = Release|Any CPU 53 | {DC2B54EB-5BF8-406A-8C1A-E49508BA7BAC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 54 | {DC2B54EB-5BF8-406A-8C1A-E49508BA7BAC}.Debug|Any CPU.Build.0 = Debug|Any CPU 55 | {DC2B54EB-5BF8-406A-8C1A-E49508BA7BAC}.Release|Any CPU.ActiveCfg = Release|Any CPU 56 | {DC2B54EB-5BF8-406A-8C1A-E49508BA7BAC}.Release|Any CPU.Build.0 = Release|Any CPU 57 | {D9311895-F541-4816-BD05-1DF39C86A01B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 58 | {D9311895-F541-4816-BD05-1DF39C86A01B}.Debug|Any CPU.Build.0 = Debug|Any CPU 59 | {D9311895-F541-4816-BD05-1DF39C86A01B}.Release|Any CPU.ActiveCfg = Release|Any CPU 60 | {D9311895-F541-4816-BD05-1DF39C86A01B}.Release|Any CPU.Build.0 = Release|Any CPU 61 | {BF689FDE-D5BE-4852-A16A-066EDE5E71B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 62 | {BF689FDE-D5BE-4852-A16A-066EDE5E71B8}.Debug|Any CPU.Build.0 = Debug|Any CPU 63 | {BF689FDE-D5BE-4852-A16A-066EDE5E71B8}.Release|Any CPU.ActiveCfg = Release|Any CPU 64 | {BF689FDE-D5BE-4852-A16A-066EDE5E71B8}.Release|Any CPU.Build.0 = Release|Any CPU 65 | {F431B580-4D6A-4658-8256-4F7AEE0AA03C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 66 | {F431B580-4D6A-4658-8256-4F7AEE0AA03C}.Debug|Any CPU.Build.0 = Debug|Any CPU 67 | {F431B580-4D6A-4658-8256-4F7AEE0AA03C}.Release|Any CPU.ActiveCfg = Release|Any CPU 68 | {F431B580-4D6A-4658-8256-4F7AEE0AA03C}.Release|Any CPU.Build.0 = Release|Any CPU 69 | {81ED4DC9-5854-432F-9723-72372189FB9D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 70 | {81ED4DC9-5854-432F-9723-72372189FB9D}.Debug|Any CPU.Build.0 = Debug|Any CPU 71 | {81ED4DC9-5854-432F-9723-72372189FB9D}.Release|Any CPU.ActiveCfg = Release|Any CPU 72 | {81ED4DC9-5854-432F-9723-72372189FB9D}.Release|Any CPU.Build.0 = Release|Any CPU 73 | EndGlobalSection 74 | GlobalSection(SolutionProperties) = preSolution 75 | HideSolutionNode = FALSE 76 | EndGlobalSection 77 | GlobalSection(NestedProjects) = preSolution 78 | {1BBD5146-9B5E-4DF8-BFB5-5B931B7E3183} = {615B001B-EF7F-4F09-B2CB-383F169E4627} 79 | {B2E29FB2-B157-4316-A38E-C99D242AE1A9} = {8F84E1A4-E5B4-4FE5-8200-E5AF0ACCE41C} 80 | {C926A148-2053-4836-B8AA-D9548C35BDC9} = {AA1D9106-BE0A-4171-AEC4-4BB6AA566DB7} 81 | {DC2B54EB-5BF8-406A-8C1A-E49508BA7BAC} = {615B001B-EF7F-4F09-B2CB-383F169E4627} 82 | {D9311895-F541-4816-BD05-1DF39C86A01B} = {633F6437-E58A-420F-AE01-7FDC6B7E2CA3} 83 | {BF689FDE-D5BE-4852-A16A-066EDE5E71B8} = {633F6437-E58A-420F-AE01-7FDC6B7E2CA3} 84 | {F431B580-4D6A-4658-8256-4F7AEE0AA03C} = {615B001B-EF7F-4F09-B2CB-383F169E4627} 85 | {81ED4DC9-5854-432F-9723-72372189FB9D} = {633F6437-E58A-420F-AE01-7FDC6B7E2CA3} 86 | EndGlobalSection 87 | GlobalSection(ExtensibilityGlobals) = postSolution 88 | SolutionGuid = {E2514CA0-588A-4092-97BB-4798EF9A6B72} 89 | EndGlobalSection 90 | EndGlobal 91 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Дуров Юрий 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Tests](https://github.com/BitzArt/ApiExceptions/actions/workflows/Tests.yml/badge.svg) 2 | 3 | 4 | # General 5 | 6 | This library defines `ApiExceptions` that you can throw in your .Net applications. 7 | 8 | # Use with Asp.Net Core 9 | 10 | > 💡 11 | > You can always refer to [this](https://github.com/BitzArt/ApiExceptions/tree/main/sample/BitzArt.ApiExceptions.AspNetCore.Sample) sample project for guidance. 12 | 13 | ## Setup: 14 | 15 | Add the nuget package: 16 | 17 | ``` 18 | dotnet add package BitzArt.ApiExceptions.AspNetCore 19 | ``` 20 | 21 | Add this line to your `Program.cs` when configuring services: 22 | ```csharp 23 | builder.Services.AddApiExceptionHandler(); 24 | ``` 25 | 26 | Add this line to your `Program.cs` when configuring the request pipeline: 27 | ```csharp 28 | // This line should go before any other middleware that might throw exceptions 29 | app.UseApiExceptionHandler(); 30 | ``` 31 | 32 | ## Usage: 33 | Then, anywhere in your code, you can throw exceptions like: 34 | ```csharp 35 | throw ApiException.BadRequest("your error message"); 36 | ``` 37 | This will stop any further execution and generate an http response with an appropriate http status code. 38 | 39 | The package handles both ApiExceptions as well as regular Exceptions. If the exception is of type `ApiException`, it will generate a response with the appropriate status code and message. If the exception is of type `Exception`, the status code will be `500`. 40 | 41 | > 💡 42 | > These responses are aligned with [RFC7807: Problem Details for HTTP APIs](https://www.rfc-editor.org/rfc/rfc7807). 43 | 44 | # Use outside of Asp.Net Core 45 | 46 | To use `ApiExceptions` in your applications, add this nuget package to your project: 47 | 48 | ``` 49 | dotnet add package BitzArt.ApiExceptions 50 | ``` 51 | 52 | This will allow you to create and throw ApiExceptions, and you can then handle them as you see fit. 53 | -------------------------------------------------------------------------------- /sample/BitzArt.ApiExceptions.AspNetCore.Sample/BitzArt.ApiExceptions.AspNetCore.Sample.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | Linux 8 | ..\.. 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /sample/BitzArt.ApiExceptions.AspNetCore.Sample/Controllers/CustomExceptionsController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace BitzArt.ApiExceptions.AspNetCore.Sample.Controllers 4 | { 5 | [ApiController] 6 | [Route("custom")] 7 | public class CustomExceptionsController : ControllerBase 8 | { 9 | [HttpGet("basic")] 10 | public IActionResult ThrowMyCustomApiException() 11 | { 12 | throw new MyCustomApiException(); 13 | } 14 | 15 | [HttpGet("payload")] 16 | public IActionResult ThrowMyCustomPayloadApiException() 17 | { 18 | throw new MyCustomPayloadApiException(); 19 | } 20 | 21 | [HttpGet("anonymous")] 22 | public IActionResult ThrowMyAnonymousPayloadApiException() 23 | { 24 | throw new MyAnonymousPayloadApiException(); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /sample/BitzArt.ApiExceptions.AspNetCore.Sample/Controllers/InnerExceptionController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace BitzArt.ApiExceptions.AspNetCore.Sample.Controllers 4 | { 5 | [ApiController] 6 | [Route("inner")] 7 | public class InnerExceptionController : ControllerBase 8 | { 9 | [HttpGet] 10 | public IActionResult ThrowExceptionWithInner() 11 | { 12 | var outter = new Exception("See inner exception for details", 13 | innerException: new("inner exception level 1", 14 | innerException: new("inner exception level 2", 15 | innerException: new ("inner exception level 3", 16 | innerException: new ("etc."))))); 17 | 18 | throw outter; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /sample/BitzArt.ApiExceptions.AspNetCore.Sample/Controllers/PredefinedExceptionsController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace BitzArt.ApiExceptions.AspNetCore.Sample.Controllers 4 | { 5 | [ApiController] 6 | [Route("predefined")] 7 | public class PredefinedExceptionsController : ControllerBase 8 | { 9 | [HttpGet("notfound")] 10 | public IActionResult ThrowNotFound() 11 | { 12 | throw ApiException.NotFound("sample error message"); 13 | } 14 | 15 | [HttpGet("badrequest")] 16 | public IActionResult ThrowBadRequest() 17 | { 18 | throw ApiException.BadRequest("sample error message"); 19 | } 20 | 21 | [HttpGet("{statusCode}")] 22 | public IActionResult ThrowUserSpecified([FromRoute] int statusCode) 23 | { 24 | throw ApiException.Custom("sample error message", statusCode); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /sample/BitzArt.ApiExceptions.AspNetCore.Sample/Controllers/SuccessfulRequestController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace BitzArt.ApiExceptions.AspNetCore.Sample.Controllers 4 | { 5 | [ApiController] 6 | [Route("success")] 7 | public class SuccessfulRequestController : ControllerBase 8 | { 9 | [HttpGet] 10 | public IActionResult ReturnOk() 11 | { 12 | return Ok("Success"); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /sample/BitzArt.ApiExceptions.AspNetCore.Sample/Exceptions/MyCustomAnonymousPayloadException.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace BitzArt.ApiExceptions.AspNetCore.Sample; 4 | 5 | public class MyAnonymousPayloadApiException : ApiExceptionBase 6 | { 7 | private class SampleInnerObject 8 | { 9 | [JsonPropertyName("value")] 10 | public string Value { get; set; } 11 | 12 | public SampleInnerObject(string value) 13 | { 14 | Value = value; 15 | } 16 | } 17 | 18 | public MyAnonymousPayloadApiException() 19 | { 20 | var extraData = new 21 | { 22 | someString = "some value", 23 | someInteger = 12345, 24 | someGuid = Guid.NewGuid(), 25 | someInnerObject = new SampleInnerObject("sample value"), 26 | someArray = new List 27 | { 28 | "object 1", 29 | "object 2", 30 | "object 3" 31 | } 32 | }; 33 | 34 | Payload.AddData(extraData); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /sample/BitzArt.ApiExceptions.AspNetCore.Sample/Exceptions/MyCustomApiException.cs: -------------------------------------------------------------------------------- 1 | namespace BitzArt.ApiExceptions.AspNetCore.Sample; 2 | 3 | public class MyCustomApiException : ApiExceptionBase 4 | { 5 | public MyCustomApiException() : base("custom error message", 420) 6 | { 7 | ErrorType = "http://example.com/link-to-error-info"; 8 | Detail = "additional details"; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /sample/BitzArt.ApiExceptions.AspNetCore.Sample/Exceptions/MyCustomPayloadApiException.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace BitzArt.ApiExceptions.AspNetCore.Sample; 4 | 5 | public class MyCustomPayloadApiException : ApiExceptionBase 6 | { 7 | public MyCustomPayloadApiException() 8 | { 9 | var extraData = new CustomExceptionData(); 10 | Payload.AddData(extraData); 11 | } 12 | 13 | private class CustomExceptionData 14 | { 15 | [JsonPropertyName("text")] 16 | public string SomeProperty { get; set; } = "some text"; 17 | 18 | [JsonPropertyName("number")] 19 | public int SomeNumber { get; set; } = 123; 20 | 21 | [JsonPropertyName("bool")] 22 | public bool SomeBool { get; set; } = true; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /sample/BitzArt.ApiExceptions.AspNetCore.Sample/Program.cs: -------------------------------------------------------------------------------- 1 | using BitzArt.ApiExceptions.AspNetCore; 2 | 3 | var builder = WebApplication.CreateBuilder(args); 4 | 5 | // Add ApiExceptionHandler to the service collection 6 | // and configure it's behavior using the options. 7 | builder.Services.AddApiExceptionHandler(options => 8 | { 9 | // Disable using default values for the 'type' field 10 | options.DisableDefaultTypeValues = true; 11 | 12 | // Enables logging of all incoming requests 13 | options.LogRequests = true; 14 | 15 | // Enables logging of handled exceptions 16 | options.LogExceptions = true; 17 | 18 | // Adds inner exceptions to error responses recursively 19 | options.DisplayInnerExceptions = true; 20 | 21 | // Disables adding the default 'status' values 22 | // (equal to http status codes) 23 | // to the ProblemDetails response 24 | options.DisableDefaultProblemDetailsStatusValue = false; 25 | }); 26 | 27 | builder.Services.AddControllers(); 28 | 29 | var app = builder.Build(); 30 | 31 | // This will add a global exception handler middleware to your request pipeline. 32 | // This middleware should be added before any other middleware that might throw exceptions. 33 | // The middleware will handle all exceptions 34 | // (including both ApiExceptions and regular Exceptions) 35 | // and return a ProblemDetails response. 36 | app.UseApiExceptionHandler(); 37 | 38 | // In this example, controllers are a source of exceptions. 39 | app.MapControllers(); 40 | 41 | app.Run(); 42 | -------------------------------------------------------------------------------- /sample/BitzArt.ApiExceptions.AspNetCore.Sample/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:49273", 7 | "sslPort": 0 8 | } 9 | }, 10 | "profiles": { 11 | "BitzArt.ApiExceptions.AspNetCore.Sample": { 12 | "commandName": "Project", 13 | "launchBrowser": false, 14 | "environmentVariables": { 15 | "ASPNETCORE_ENVIRONMENT": "Development" 16 | }, 17 | "applicationUrl": "http://localhost:80", 18 | "dotnetRunMessages": true 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /sample/BitzArt.ApiExceptions.AspNetCore.Sample/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /sample/BitzArt.ApiExceptions.AspNetCore.Sample/requests.http: -------------------------------------------------------------------------------- 1 | # You can run the sample WebApi on your machine 2 | # and use these requests to try ApiExceptions in action! 3 | 4 | ### Successful request 5 | GET http://localhost:80/success 6 | 7 | ### ========= Predefined exceptions ========= 8 | 9 | ### NotFound 10 | GET http://localhost:80/predefined/notfound 11 | ### BadRequest 12 | GET http://localhost:80/predefined/badrequest 13 | ### Custom status code 14 | GET http://localhost:80/predefined/501 15 | 16 | ### ========= Custom exceptions ========= 17 | 18 | ### Basic 19 | GET http://localhost:80/custom/basic 20 | 21 | ### Payload 22 | GET http://localhost:80/custom/payload 23 | 24 | ### Anonymous 25 | GET http://localhost:80/custom/anonymous 26 | 27 | ### ========= Inner Exceptions ========= 28 | 29 | ### Inner 30 | GET http://localhost:80/inner -------------------------------------------------------------------------------- /src/BitzArt.ApiExceptions.AspNetCore/Attributes/ApiExceptionFilterAttribute.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc.Filters; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Microsoft.Extensions.Logging; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using BitzArt.ApiExceptions.AspNetCore; 6 | using System.Diagnostics; 7 | 8 | namespace BitzArt.ApiExceptions; 9 | 10 | /// 11 | /// This attribute allows for the handling of exceptions thrown by the MVC controller. 12 | /// 13 | public class ApiExceptionFilterAttribute : ExceptionFilterAttribute 14 | { 15 | private static ApiExceptionHandlerOptions? _options; 16 | private static ILogger? _logger; 17 | 18 | /// 19 | /// Handles the exception and returns a problem details response. 20 | /// 21 | /// 22 | public override void OnException(ExceptionContext context) 23 | { 24 | var httpContext = context.HttpContext; 25 | 26 | _options ??= httpContext.RequestServices.GetService(); 27 | _options ??= new(); 28 | 29 | _logger ??= httpContext.RequestServices.GetRequiredService>(); 30 | 31 | var exception = context.Exception; 32 | 33 | var problem = exception.GetProblemDetails(httpContext, _options); 34 | context.Result = new ObjectResult(problem); 35 | 36 | if (_options.LogRequests) 37 | { 38 | var req = httpContext.Request; 39 | _logger.LogInformation("{timestamp} {method} {path} : {statusCode}", string.Format("{0:u}", DateTime.Now), req.Method, req.Path, httpContext.Response.StatusCode); 40 | } 41 | if (_options.LogExceptions) 42 | { 43 | _logger.LogError("{exception}", exception.ToStringDemystified()); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/BitzArt.ApiExceptions.AspNetCore/BitzArt.ApiExceptions.AspNetCore.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net6.0;net7.0;net8.0 5 | BitzArt.ApiExceptions.AspNetCore 6 | BitzArt.ApiExceptions.AspNetCore 7 | enable 8 | enable 9 | true 10 | 11 | BitzArt.ApiExceptions.AspNetCore 12 | BitzArt 13 | ApiExceptions Asp.Net Core implementation 14 | MIT 15 | git 16 | https://github.com/BitzArt/ApiExceptions 17 | https://github.com/BitzArt/ApiExceptions 18 | README.md 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | <_Parameter1>BitzArt.ApiExceptions.AspNetCore.Tests 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /src/BitzArt.ApiExceptions.AspNetCore/Config.cs: -------------------------------------------------------------------------------- 1 | namespace BitzArt.ApiExceptions.AspNetCore 2 | { 3 | internal static partial class Config 4 | { 5 | public const string DocumentationLink = "https://developer.mozilla.org/en-US/docs/Web/HTTP/Status"; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/BitzArt.ApiExceptions.AspNetCore/Extensions/AddApiExceptionHandlerExtension.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | 3 | namespace BitzArt.ApiExceptions.AspNetCore; 4 | 5 | /// 6 | /// Contains extension methods for adding the API exception handler to the service collection. 7 | /// 8 | public static class AddApiExceptionHandlerExtension 9 | { 10 | /// 11 | /// Adds the API exception handler and all required services to the service collection. 12 | /// 13 | public static IServiceCollection AddApiExceptionHandler 14 | (this IServiceCollection services, Action? configure = null) 15 | => services.AddApiExceptionHandler(configure); 16 | 17 | /// 18 | /// Adds a custom API exception handler and all required services to the service collection. 19 | /// 20 | public static IServiceCollection AddApiExceptionHandler 21 | (this IServiceCollection services, Action? configure = null) 22 | where THandler : class, IApiExceptionHandler 23 | { 24 | services.AddHttpContextAccessor(); 25 | 26 | ApiExceptionHandlerOptions options = new(); 27 | configure?.Invoke(options); 28 | services.AddSingleton(options); 29 | 30 | services.AddScoped(); 31 | 32 | return services; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/BitzArt.ApiExceptions.AspNetCore/Extensions/ApiExceptionExtensions.cs: -------------------------------------------------------------------------------- 1 | using BitzArt.ApiExceptions; 2 | using BitzArt.ApiExceptions.AspNetCore; 3 | using Microsoft.AspNetCore.Http; 4 | 5 | namespace System; 6 | 7 | internal static class ApiExceptionExtensions 8 | { 9 | internal static ProblemDetails GetProblemDetails(this ApiExceptionBase apiException, HttpContext httpContext, ApiExceptionHandlerOptions options) 10 | { 11 | httpContext.Response.ContentType = "application/problem+json"; 12 | httpContext.Response.StatusCode = apiException.StatusCode; 13 | 14 | var defaultErrorType = apiException.GetDefaultErrorType(options); 15 | if (defaultErrorType is not null) apiException.ErrorType = defaultErrorType; 16 | 17 | return new ProblemDetails(apiException, addInner: options.DisplayInnerExceptions); 18 | } 19 | 20 | internal static string? GetDefaultErrorType(this ApiExceptionBase apiException, ApiExceptionHandlerOptions options) 21 | { 22 | if (apiException.ErrorType is not null) return null; 23 | 24 | var useDefaultTypeValue = apiException.GetUseDefaultTypeValue(options); 25 | if (!useDefaultTypeValue) return null; 26 | 27 | var link = $"{Config.DocumentationLink}/{apiException.StatusCode}"; 28 | return link; 29 | } 30 | 31 | internal static bool GetUseDefaultTypeValue(this ApiExceptionBase apiException, ApiExceptionHandlerOptions options) 32 | { 33 | if (options.DisableDefaultTypeValues) return false; 34 | 35 | var value = apiException.UseDefaultErrorTypeValue; 36 | 37 | if (value is null) return true; 38 | 39 | return value.Value; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/BitzArt.ApiExceptions.AspNetCore/Extensions/ExceptionExtensions.cs: -------------------------------------------------------------------------------- 1 | using BitzArt.ApiExceptions; 2 | using BitzArt.ApiExceptions.AspNetCore; 3 | using Microsoft.AspNetCore.Http; 4 | using System.Net; 5 | 6 | namespace System; 7 | 8 | internal static class ExceptionExtensions 9 | { 10 | internal static int GetHttpStatusCode(this Exception exception) 11 | { 12 | if (exception is ApiExceptionBase apiException) return apiException.StatusCode; 13 | return (int)HttpStatusCode.InternalServerError; 14 | } 15 | 16 | internal static ProblemDetails GetProblemDetails(this Exception exception, HttpContext httpContext, ApiExceptionHandlerOptions options) 17 | { 18 | if (exception is ApiExceptionBase apiException) return apiException.GetProblemDetails(httpContext, options); 19 | 20 | httpContext.Response.ContentType = "application/problem+json"; 21 | httpContext.Response.StatusCode = 500; 22 | return new ProblemDetails(exception, addInner: options.DisplayInnerExceptions); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/BitzArt.ApiExceptions.AspNetCore/Extensions/UseApiExceptionHandlerExtension.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | 3 | namespace BitzArt.ApiExceptions.AspNetCore; 4 | 5 | /// 6 | /// Contains extension methods for adding the API exception handler middleware. 7 | /// 8 | public static class UseApiExceptionHandlerExtension 9 | { 10 | /// 11 | /// Configures the middleware to handle exceptions and return a problem details response. 12 | /// 13 | /// 14 | public static void UseApiExceptionHandler(this IApplicationBuilder app) 15 | { 16 | app.UseMiddleware(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/BitzArt.ApiExceptions.AspNetCore/Handlers/ApiExceptionHandler.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Http; 2 | using Microsoft.Extensions.Logging; 3 | using System.Diagnostics; 4 | using System.Text.Json; 5 | 6 | namespace BitzArt.ApiExceptions.AspNetCore; 7 | 8 | /// 9 | /// Default implementation. 10 | /// 11 | public class ApiExceptionHandler : IApiExceptionHandler 12 | { 13 | private readonly ApiExceptionHandlerOptions _options; 14 | private readonly HttpContext _httpContext; 15 | private readonly ILogger _requestLogger; 16 | private readonly ILogger _exceptionLogger; 17 | 18 | /// 19 | /// Initializes a new instance of the class. 20 | /// 21 | public ApiExceptionHandler( 22 | ApiExceptionHandlerOptions options, 23 | IHttpContextAccessor contextAccessor, 24 | ILoggerFactory loggerFactory) 25 | { 26 | _options = options; 27 | _httpContext = contextAccessor.HttpContext!; 28 | _requestLogger = loggerFactory.CreateLogger("Request"); 29 | _exceptionLogger = loggerFactory.CreateLogger("ExceptionHandler"); 30 | } 31 | 32 | /// 33 | /// Handles the exception and returns a problem details response. 34 | /// 35 | public virtual async Task HandleAsync(Exception exception) 36 | { 37 | var problem = exception.GetProblemDetails(_httpContext, _options); 38 | 39 | if (!_options.DisableDefaultProblemDetailsStatusValue) 40 | { 41 | problem.Status ??= _httpContext.Response.StatusCode; 42 | } 43 | 44 | await _httpContext.Response.WriteAsync(JsonSerializer.Serialize(problem)); 45 | 46 | if (_options.LogRequests) 47 | { 48 | var req = _httpContext.Request; 49 | _requestLogger.LogInformation("{timestamp} {method} {path} : {statusCode}", string.Format("{0:u}", DateTime.Now), req.Method, req.Path, _httpContext.Response.StatusCode); 50 | } 51 | if (_options.LogExceptions) 52 | { 53 | _exceptionLogger.LogError(exception, "{exception}", exception.ToStringDemystified()); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/BitzArt.ApiExceptions.AspNetCore/Middleware/ApiExceptionHandlingMiddleware.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Http; 2 | using Microsoft.Extensions.Logging; 3 | 4 | namespace BitzArt.ApiExceptions.AspNetCore; 5 | 6 | internal class ApiExceptionHandlingMiddleware 7 | { 8 | private readonly RequestDelegate _next; 9 | private readonly ApiExceptionHandlerOptions _options; 10 | private readonly ILogger _requestLogger; 11 | 12 | public ApiExceptionHandlingMiddleware(RequestDelegate next, ApiExceptionHandlerOptions options, ILoggerFactory loggerFactory) 13 | { 14 | _next = next; 15 | _options = options; 16 | _requestLogger = loggerFactory.CreateLogger("Request"); 17 | } 18 | 19 | public virtual async Task InvokeAsync(HttpContext context, IApiExceptionHandler handler) 20 | { 21 | try 22 | { 23 | await _next(context); 24 | 25 | if (_options.LogRequests) 26 | { 27 | var req = context.Request; 28 | _requestLogger.LogInformation("{timestamp} {method} {path} : 200", string.Format("{0:u}", DateTime.Now), req.Method, req.Path); 29 | } 30 | } 31 | catch (Exception ex) 32 | { 33 | await handler.HandleAsync(ex); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/BitzArt.ApiExceptions.AspNetCore/Models/ApiExceptionHandlerOptions.cs: -------------------------------------------------------------------------------- 1 | namespace BitzArt.ApiExceptions.AspNetCore; 2 | 3 | /// 4 | /// Allows configuring the API exception handler's behavior. 5 | /// 6 | public class ApiExceptionHandlerOptions 7 | { 8 | /// 9 | /// Enables logging for all requests.
10 | /// ⚠️ Will not log successful requests if ApiExceptionHandlingMiddleware is not enabled.
11 | /// Default: false 12 | ///
13 | public bool LogRequests { get; set; } = false; 14 | 15 | /// 16 | /// Enables logging of handled exceptions.
17 | /// Default: false 18 | ///
19 | public bool LogExceptions { get; set; } = false; 20 | 21 | /// 22 | /// Adds inner exceptions to ProblemDetails responses recursively.
23 | /// Default: false 24 | ///
25 | public bool DisplayInnerExceptions { get; set; } = false; 26 | 27 | /// 28 | /// Disables using default values for 'type' field in the ProblemDetails response.
29 | /// Default: false 30 | ///
31 | public bool DisableDefaultTypeValues { get; set; } = false; 32 | 33 | /// 34 | /// Disables adding the default 'status' values to the ProblemDetails response.
35 | /// Default 'status' values are based on the http status codes.
36 | /// Default: false 37 | ///
38 | public bool DisableDefaultProblemDetailsStatusValue { get; set; } = false; 39 | } 40 | -------------------------------------------------------------------------------- /src/BitzArt.ApiExceptions.AspNetCore/Models/ProblemDetails.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | using Keys = BitzArt.ApiExceptions.ApiExceptionPayload.Keys; 3 | 4 | namespace BitzArt.ApiExceptions; 5 | 6 | /// 7 | /// Problem Details, as defined in RFC 7807. 8 | /// 9 | public class ProblemDetails 10 | { 11 | private static IEnumerable ReservedKeys => new List 12 | { 13 | Keys.Title, 14 | Keys.ErrorType, 15 | Keys.Detail, 16 | Keys.Instance 17 | }; 18 | 19 | /// 20 | /// Provides a short, human-readable summary of the problem. 21 | /// 22 | [JsonPropertyName(Keys.Title)] 23 | [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] 24 | public string? Title { get; set; } 25 | 26 | /// 27 | /// The HTTP status code generated by the origin server for this occurrence of the problem. 28 | /// 29 | [JsonPropertyName(Keys.Status)] 30 | [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] 31 | public int? Status { get; set; } 32 | 33 | /// 34 | /// A URI reference [RFC3986] that identifies the problem type. 35 | /// 36 | [JsonPropertyName(Keys.ErrorType)] 37 | [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] 38 | public string? ErrorType { get; set; } 39 | 40 | /// 41 | /// A human-readable explanation specific to this occurrence of the problem. 42 | /// 43 | [JsonPropertyName(Keys.Detail)] 44 | [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] 45 | public string? Detail { get; set; } 46 | 47 | /// 48 | /// A URI reference that identifies the specific occurrence of the problem. 49 | /// It may or may not yield further information if dereferenced. 50 | /// 51 | [JsonPropertyName(Keys.Instance)] 52 | [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] 53 | public string? Instance { get; set; } 54 | 55 | /// 56 | /// Additional response data. 57 | /// 58 | [JsonExtensionData] 59 | public IDictionary Extensions { get; set; } 60 | 61 | /// 62 | /// Creates a new instance of from an ApiException. 63 | /// 64 | /// The exception indicating an API error 65 | /// Whether or not to parse inner exceptions 66 | public ProblemDetails(ApiExceptionBase exception, bool addInner = false) 67 | : this(exception, exception.Payload.Data, addInner) 68 | { 69 | } 70 | 71 | /// 72 | /// Creates a new instance of from an . 73 | /// 74 | /// The exception indicating an API error 75 | /// Additional response data 76 | /// Whether or not to parse inner exceptions 77 | public ProblemDetails(Exception exception, IDictionary? data = null, bool addInner = false) 78 | : this(exception.Message, data) 79 | { 80 | if (addInner) 81 | { 82 | var dict = AddInner(exception); 83 | if (dict is null) return; 84 | Extensions.Add("inner", dict); 85 | } 86 | } 87 | 88 | // Adds inner exceptions recursively 89 | private static Dictionary? AddInner(Exception exception) 90 | { 91 | var inner = exception.InnerException; 92 | 93 | if (inner is null) return null; 94 | var dict = new Dictionary 95 | { 96 | { "title", inner.Message } 97 | }; 98 | 99 | var next = AddInner(inner); 100 | if (next is not null) dict["inner"] = next; 101 | 102 | return dict; 103 | } 104 | 105 | /// 106 | /// Creates a new instance of with a specified error message. 107 | /// 108 | /// The error message 109 | /// Additional response data 110 | public ProblemDetails(string? message = null, IDictionary? data = null) 111 | { 112 | Extensions = new Dictionary(); 113 | ParseData(data); 114 | if (!string.IsNullOrWhiteSpace(message)) Title = message; 115 | } 116 | 117 | private void ParseData(IDictionary? data) 118 | { 119 | if (data is null) return; 120 | 121 | if (data.TryGetValue(Keys.ErrorType, out object? errorType)) ErrorType = (string)errorType; 122 | if (data.TryGetValue(Keys.Detail, out object? detail)) Detail = (string)detail; 123 | if (data.TryGetValue(Keys.Instance, out object? instance)) Instance = (string)instance; 124 | 125 | foreach (var entry in data) 126 | { 127 | if (ReservedKeys.Contains(entry.Key)) continue; 128 | Extensions.Add(entry.Key, entry.Value); 129 | } 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /src/BitzArt.ApiExceptions.OpenTelemetry/BitzArt.ApiExceptions.OpenTelemetry.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0;net7.0;net8.0 5 | BitzArt.ApiExceptions.OpenTelemetry 6 | BitzArt.ApiExceptions.OpenTelemetry 7 | enable 8 | enable 9 | true 10 | 11 | BitzArt.ApiExceptions.OpenTelemetry 12 | BitzArt 13 | ApiExceptions meets OpenTelemetry 14 | MIT 15 | git 16 | https://github.com/BitzArt/ApiExceptions 17 | https://github.com/BitzArt/ApiExceptions 18 | README.md 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | <_Parameter1>BitzArt.ApiExceptions.OpenTelemetry.Tests 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /src/BitzArt.ApiExceptions.OpenTelemetry/ExceptionTelemetry.cs: -------------------------------------------------------------------------------- 1 | using OpenTelemetry.Trace; 2 | using System.Diagnostics; 3 | using System.Runtime.ExceptionServices; 4 | 5 | namespace BitzArt; 6 | 7 | public static partial class ExceptionTelemetry 8 | { 9 | /// 10 | /// This method will enable reporting of all exceptions that were raised 11 | /// in your application to OpenTelemetry. 12 | /// 13 | public static void EnableOpenTelemetry() 14 | { 15 | AppDomain.CurrentDomain.FirstChanceException += RecordExceptionThrown; 16 | } 17 | 18 | private static void RecordExceptionThrown(object? sender, FirstChanceExceptionEventArgs e) 19 | { 20 | var activity = Activity.Current; 21 | var ex = e.Exception; 22 | 23 | if (activity is null || e is null) return; 24 | 25 | if (!activity!.Events.Any(x => x.Name == "exception" && 26 | x.Tags.Any(xx => 27 | xx.Key == "exception.message" 28 | && (string)xx.Value! == ex.Message))) 29 | { 30 | activity.RecordException(ex); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/BitzArt.ApiExceptions/ApiException.cs: -------------------------------------------------------------------------------- 1 | using BitzArt.ApiExceptions; 2 | 3 | namespace BitzArt; 4 | 5 | /// 6 | /// Allows for easy creation of API exceptions. 7 | /// 8 | public static partial class ApiException 9 | { 10 | /// 11 | /// Creates a new instance of 12 | /// 13 | /// 14 | /// 15 | /// 16 | /// 17 | /// 18 | /// 19 | public static CustomApiException Custom 20 | (string message, ApiStatusCode statusCode = ApiStatusCode.Error, string? errorType = null, ApiExceptionPayload? payload = null, Exception? innerException = null) 21 | => new(message, statusCode, errorType, payload, innerException); 22 | 23 | /// 24 | /// Creates a new instance of 25 | /// 26 | /// 27 | /// 28 | /// 29 | /// 30 | /// 31 | /// 32 | public static CustomApiException Custom 33 | (string message, int statusCode, string? errorType = null, ApiExceptionPayload? payload = null, Exception? innerException = null) 34 | => new(message, statusCode, errorType, payload, innerException); 35 | 36 | /// 37 | /// Creates a new instance of 38 | /// 39 | /// 40 | /// 41 | /// 42 | /// 43 | /// 44 | public static InternalErrorApiException InternalError 45 | (string message, string? errorType = null, ApiExceptionPayload? payload = null, Exception? innerException = null) 46 | => new(message, errorType, payload, innerException); 47 | 48 | /// 49 | /// Creates a new instance of 50 | /// 51 | /// 52 | /// 53 | /// 54 | /// 55 | /// 56 | public static BadRequestApiException BadRequest 57 | (string message, string? errorType = null, ApiExceptionPayload? payload = null, Exception? innerException = null) 58 | => new(message, errorType, payload, innerException); 59 | 60 | /// 61 | /// Creates a new instance of 62 | /// 63 | /// 64 | /// 65 | /// 66 | /// 67 | /// 68 | public static ConflictApiException Conflict 69 | (string message, string? errorType = null, ApiExceptionPayload? payload = null, Exception? innerException = null) 70 | => new(message, errorType, payload, innerException); 71 | 72 | /// 73 | /// Creates a new instance of 74 | /// 75 | /// 76 | /// 77 | /// 78 | /// 79 | /// 80 | public static ForbiddenApiException Forbidden 81 | (string message, string? errorType = null, ApiExceptionPayload? payload = null, Exception? innerException = null) 82 | => new(message, errorType, payload, innerException); 83 | 84 | /// 85 | /// Creates a new instance of 86 | /// 87 | /// 88 | /// 89 | /// 90 | /// 91 | /// 92 | public static MethodNotAllowedApiException MethodNotAllowed 93 | (string message, string? errorType = null, ApiExceptionPayload? payload = null, Exception? innerException = null) 94 | => new(message, errorType, payload, innerException); 95 | 96 | /// 97 | /// Creates a new instance of 98 | /// 99 | /// 100 | /// 101 | /// 102 | /// 103 | /// 104 | public static NoContentApiException NoContent 105 | (string message, string? errorType = null, ApiExceptionPayload? payload = null, Exception? innerException = null) 106 | => new(message, errorType, payload, innerException); 107 | 108 | /// 109 | /// Creates a new instance of 110 | /// 111 | /// 112 | /// 113 | /// 114 | /// 115 | /// 116 | public static NotFoundApiException NotFound 117 | (string message, string? errorType = null, ApiExceptionPayload? payload = null, Exception? innerException = null) 118 | => new(message, errorType, payload, innerException); 119 | 120 | /// 121 | /// Creates a new instance of 122 | /// 123 | /// 124 | /// 125 | /// 126 | /// 127 | /// 128 | public static UnauthorizedApiException Unauthorized 129 | (string message, string? errorType = null, ApiExceptionPayload? payload = null, Exception? innerException = null) 130 | => new(message, errorType, payload, innerException); 131 | } 132 | -------------------------------------------------------------------------------- /src/BitzArt.ApiExceptions/BitzArt.ApiExceptions.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net6.0;net7.0;net8.0 5 | BitzArt.ApiExceptions 6 | BitzArt.ApiExceptions 7 | enable 8 | enable 9 | true 10 | 11 | BitzArt.ApiExceptions 12 | BitzArt 13 | Reinventing C# exceptions 14 | MIT 15 | git 16 | https://github.com/BitzArt/ApiExceptions 17 | https://github.com/BitzArt/ApiExceptions 18 | README.md 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | <_Parameter1>BitzArt.ApiExceptions.Tests 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /src/BitzArt.ApiExceptions/Enum/ApiStatusCode.cs: -------------------------------------------------------------------------------- 1 | namespace BitzArt.ApiExceptions; 2 | 3 | /// 4 | /// API status codes. 5 | /// 6 | public enum ApiStatusCode : int 7 | { 8 | /// 9 | /// Success API status code. 10 | /// 11 | OK = 200, 12 | 13 | /// 14 | /// Created API status code. 15 | /// 16 | Created = 201, 17 | 18 | /// 19 | /// Accepted API status code. 20 | /// 21 | Accepted = 202, 22 | 23 | /// 24 | /// No content API status code. 25 | /// 26 | NoContent = 204, 27 | 28 | 29 | /// 30 | /// Bad request API status code. 31 | /// 32 | BadRequest = 400, 33 | 34 | /// 35 | /// Unauthorized API status code. 36 | /// 37 | Unauthorized = 401, 38 | 39 | /// 40 | /// Payment required API status code. 41 | /// 42 | PaymentRequired = 402, 43 | 44 | /// 45 | /// Forbidden API status code. 46 | /// 47 | Forbidden = 403, 48 | 49 | /// 50 | /// Not found API status code. 51 | /// 52 | NotFound = 404, 53 | 54 | /// 55 | /// Method not allowed API status code. 56 | /// 57 | MethodNotAllowed = 405, 58 | 59 | /// 60 | /// Not acceptable API status code. 61 | /// 62 | NotAcceptable = 406, 63 | 64 | /// 65 | /// Conflict API status code. 66 | /// 67 | Conflict = 409, 68 | 69 | /// 70 | /// Failed dependency API status code. 71 | /// 72 | FailedDependency = 424, 73 | 74 | /// 75 | /// Too many requests API status code. 76 | /// 77 | TooManyRequests = 429, 78 | 79 | /// 80 | /// Error API status code. 81 | /// 82 | Error = 500, 83 | 84 | /// 85 | /// NotImplemented API status code. 86 | /// 87 | NotImplemented = 501, 88 | 89 | /// 90 | /// Service unavailable API status code. 91 | /// 92 | ServiceUnavailable = 503, 93 | } 94 | -------------------------------------------------------------------------------- /src/BitzArt.ApiExceptions/Extensions/ObjectParsingExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json; 2 | 3 | namespace BitzArt.ApiExceptions; 4 | 5 | internal static class ObjectParsingExtensions 6 | { 7 | internal static IEnumerable>? ParseAsExtensions(this object? value) 8 | { 9 | var json = JsonSerializer.Serialize(value); 10 | return JsonSerializer.Deserialize>(json); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/BitzArt.ApiExceptions/Interface/IApiExceptionHandler.cs: -------------------------------------------------------------------------------- 1 | namespace BitzArt.ApiExceptions; 2 | 3 | /// 4 | /// API exception handler. 5 | /// 6 | public interface IApiExceptionHandler 7 | { 8 | /// 9 | /// Handles the exception, whether it is an ApiException or a regular 10 | /// 11 | Task HandleAsync(Exception exception); 12 | } -------------------------------------------------------------------------------- /src/BitzArt.ApiExceptions/Models/ApiExceptionBase.cs: -------------------------------------------------------------------------------- 1 | using Keys = BitzArt.ApiExceptions.ApiExceptionPayload.Keys; 2 | 3 | namespace BitzArt.ApiExceptions; 4 | 5 | /// 6 | /// API Exception base class. 7 | /// 8 | public abstract partial class ApiExceptionBase : Exception 9 | { 10 | /// 11 | /// API Status code 12 | /// 13 | public int StatusCode { get; set; } 14 | 15 | /// 16 | /// API Exception Payload 17 | /// 18 | public ApiExceptionPayload Payload { get; } 19 | 20 | /// 21 | /// Creates a new instance of 22 | /// 23 | /// 24 | /// 25 | /// 26 | /// 27 | /// 28 | protected ApiExceptionBase 29 | ( 30 | string message = "Unexpected Error", 31 | ApiStatusCode statusCode = ApiStatusCode.Error, 32 | string? errorType = null, 33 | ApiExceptionPayload? payload = null, 34 | Exception? innerException = null) 35 | : this(message, (int)statusCode, errorType, payload, innerException) 36 | { } 37 | 38 | /// 39 | /// Creates a new instance of 40 | /// 41 | /// 42 | /// 43 | /// 44 | /// 45 | /// 46 | protected ApiExceptionBase 47 | ( 48 | string message, 49 | int statusCode, 50 | string? errorType = null, 51 | ApiExceptionPayload? payload = null, 52 | Exception? innerException = null) 53 | : base(message, innerException) 54 | { 55 | StatusCode = statusCode; 56 | Payload = payload ?? new(); 57 | if (errorType is not null) ErrorType = errorType; 58 | } 59 | 60 | /// 61 | /// Error type 62 | /// 63 | public string? ErrorType 64 | { 65 | get => Payload.GetDataEntry(Keys.ErrorType); 66 | set => Payload.AddData(Keys.ErrorType, value!); 67 | } 68 | 69 | /// 70 | /// Additional error details 71 | /// 72 | public string? Detail 73 | { 74 | get => Payload.GetDataEntry(Keys.Detail); 75 | set => Payload.AddData(Keys.Detail, value!); 76 | } 77 | 78 | /// 79 | /// A reference that identifies the specific occurrence of the error 80 | /// 81 | public string? Instance 82 | { 83 | get => Payload.GetDataEntry(Keys.Instance); 84 | set => Payload.AddData(Keys.Instance, value!); 85 | } 86 | 87 | /// 88 | /// Whether or not to use the default error type value 89 | /// 90 | public bool? UseDefaultErrorTypeValue 91 | { 92 | get => Payload.GetConfigurationEntry(Keys.UseDefaultErrorType); 93 | set => Payload.AddConfiguration(Keys.UseDefaultErrorType, value!); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/BitzArt.ApiExceptions/Models/ApiExceptionPayload.cs: -------------------------------------------------------------------------------- 1 | namespace BitzArt.ApiExceptions; 2 | 3 | /// 4 | /// API Exception Payload, used to add additional data to the exception. 5 | /// 6 | public partial class ApiExceptionPayload 7 | { 8 | /// 9 | /// Registered keys for a ProblemDetails payload. 10 | /// 11 | public static class Keys 12 | { 13 | /// 14 | /// ProblemDetails.Title 15 | /// 16 | public const string Title = "title"; 17 | /// 18 | /// ProblemDetails.Status 19 | /// 20 | public const string Status = "status"; 21 | /// 22 | /// ProblemDetails.ErrorType 23 | /// 24 | public const string ErrorType = "type"; 25 | /// 26 | /// ProblemDetails.Detail 27 | /// 28 | public const string Detail = "detail"; 29 | /// 30 | /// ProblemDetails.Instance 31 | /// 32 | public const string Instance = "instance"; 33 | /// 34 | /// UseDefaultErrorType 35 | /// 36 | public const string UseDefaultErrorType = "useDefaultType"; 37 | } 38 | 39 | /// 40 | /// Custom data for the error response. 41 | /// 42 | public IDictionary Data { get; } 43 | 44 | /// 45 | /// Custom configurations for the error response creation. 46 | /// 47 | public IDictionary Configurations { get; } 48 | 49 | /// 50 | /// Creates a new instance of . 51 | /// 52 | /// 53 | public ApiExceptionPayload(object data) : this() 54 | { 55 | AddData(data); 56 | } 57 | 58 | /// 59 | /// Creates a new instance of . 60 | /// 61 | public ApiExceptionPayload() 62 | { 63 | Data = new Dictionary(); 64 | Configurations = new Dictionary(); 65 | } 66 | 67 | /// 68 | /// Creates a new instance of . 69 | /// 70 | /// 71 | public ApiExceptionPayload(IEnumerable> data) 72 | { 73 | Data = new Dictionary(data); 74 | Configurations = new Dictionary(); 75 | } 76 | 77 | /// 78 | /// Creates a new instance of . 79 | /// 80 | /// 81 | public ApiExceptionPayload(IDictionary data) 82 | { 83 | Data = data; 84 | Configurations = new Dictionary(); 85 | } 86 | 87 | /// 88 | /// Adds custom data to the payload. 89 | /// 90 | /// 91 | public void AddData(object data) 92 | { 93 | var parsed = data.ParseAsExtensions(); 94 | if (parsed is null || !parsed.Any()) return; 95 | AddData(parsed); 96 | } 97 | 98 | /// 99 | /// Adds custom configurations to the payload. 100 | /// 101 | /// 102 | public void AddConfiguration(object data) 103 | { 104 | var parsed = data.ParseAsExtensions(); 105 | if (parsed is null || !parsed.Any()) return; 106 | AddConfiguration(parsed); 107 | } 108 | 109 | /// 110 | /// Adds custom data to the payload. 111 | /// 112 | /// 113 | public void AddData(IEnumerable> data) 114 | { 115 | foreach (var entry in data) AddData(entry); 116 | } 117 | 118 | /// 119 | /// Adds custom configurations to the payload. 120 | /// 121 | /// 122 | public void AddConfiguration(IEnumerable> data) 123 | { 124 | foreach (var entry in data) AddConfiguration(entry); 125 | } 126 | 127 | /// 128 | /// Adds custom data to the payload. 129 | /// 130 | /// 131 | public void AddData(KeyValuePair entry) 132 | => AddData(entry.Key, entry.Value); 133 | 134 | /// 135 | /// Adds custom configurations to the payload. 136 | /// 137 | /// 138 | public void AddConfiguration(KeyValuePair entry) 139 | => AddConfiguration(entry.Key, entry.Value); 140 | 141 | /// 142 | /// Adds custom data to the payload. 143 | /// 144 | /// 145 | /// 146 | public void AddData(string key, object value) 147 | => AddEntry(Data, key, value); 148 | 149 | /// 150 | /// Adds custom configurations to the payload. 151 | /// 152 | /// 153 | /// 154 | public void AddConfiguration(string key, object value) 155 | => AddEntry(Configurations, key, value); 156 | 157 | private static void AddEntry(IDictionary dict, string key, object value) 158 | { 159 | if (value is null) return; 160 | dict[key] = value; 161 | } 162 | 163 | /// 164 | /// Retrieves custom data from the payload. 165 | /// 166 | /// 167 | /// 168 | /// 169 | public T GetDataEntry(string key) 170 | => GetEntry(Data, key); 171 | 172 | /// 173 | /// Retrieves custom configurations from the payload. 174 | /// 175 | /// 176 | /// 177 | /// 178 | public T GetConfigurationEntry(string key) 179 | => GetEntry(Configurations, key); 180 | 181 | private static T GetEntry(IDictionary dict, string key) 182 | { 183 | if (!dict.ContainsKey(key)) return default!; 184 | 185 | var value = dict 186 | .Where(x => x.Key == key) 187 | .Single() 188 | .Value; 189 | 190 | if (value is not T) throw new Exception($"'{key}' is not a {typeof(T).Name}"); 191 | 192 | return (T)value; 193 | } 194 | } 195 | -------------------------------------------------------------------------------- /src/BitzArt.ApiExceptions/Models/PredefinedExceptions.cs: -------------------------------------------------------------------------------- 1 | namespace BitzArt.ApiExceptions; 2 | 3 | /// 4 | /// Represents a custom API exception. 5 | /// 6 | public class CustomApiException : ApiExceptionBase 7 | { 8 | /// 9 | /// Creates a new 10 | /// 11 | public CustomApiException(string message, ApiStatusCode statusCode = ApiStatusCode.Error, string? errorType = null, ApiExceptionPayload? payload = null, Exception? innerException = null) 12 | : this(message, (int)statusCode, errorType, payload, innerException) 13 | { } 14 | 15 | /// 16 | /// Creates a new 17 | /// 18 | /// 19 | /// 20 | /// 21 | /// 22 | /// 23 | public CustomApiException(string message, int statusCode, string? errorType = null, ApiExceptionPayload? payload = null, Exception? innerException = null) 24 | : base(message, statusCode, errorType, payload, innerException) 25 | { } 26 | 27 | } 28 | 29 | /// 30 | /// Represents an internal error API exception. 31 | /// 32 | public class InternalErrorApiException : ApiExceptionBase 33 | { 34 | /// 35 | /// Creates a new 36 | /// 37 | /// 38 | /// 39 | /// 40 | /// 41 | public InternalErrorApiException(string message = "Internal error", string? errorType = null, ApiExceptionPayload? payload = null, Exception? innerException = null) 42 | : base(message, ApiStatusCode.Error, errorType, payload, innerException) 43 | { } 44 | } 45 | 46 | /// 47 | /// Represents a bad request API exception. 48 | /// 49 | public class BadRequestApiException : ApiExceptionBase 50 | { 51 | /// 52 | /// Creates a new 53 | /// 54 | /// 55 | /// 56 | /// 57 | /// 58 | public BadRequestApiException(string message = "Bad request", string? errorType = null, ApiExceptionPayload? payload = null, Exception? innerException = null) 59 | : base(message, ApiStatusCode.BadRequest, errorType, payload, innerException) 60 | { } 61 | } 62 | 63 | /// 64 | /// Represents a conflict API exception. 65 | /// 66 | public class ConflictApiException : ApiExceptionBase 67 | { 68 | /// 69 | /// Creates a new 70 | /// 71 | /// 72 | /// 73 | /// 74 | /// 75 | public ConflictApiException(string message = "Conflict", string? errorType = null, ApiExceptionPayload? payload = null, Exception? innerException = null) 76 | : base(message, ApiStatusCode.Conflict, errorType, payload, innerException) 77 | { } 78 | } 79 | 80 | /// 81 | /// Represents a forbidden API exception. 82 | /// 83 | public class ForbiddenApiException : ApiExceptionBase 84 | { 85 | /// 86 | /// Creates a new 87 | /// 88 | /// 89 | /// 90 | /// 91 | /// 92 | public ForbiddenApiException(string message = "Forbidden", string? errorType = null, ApiExceptionPayload? payload = null, Exception? innerException = null) 93 | : base(message, ApiStatusCode.Forbidden, errorType, payload, innerException) 94 | { } 95 | } 96 | 97 | /// 98 | /// Represents a method not allowed API exception. 99 | /// 100 | public class MethodNotAllowedApiException : ApiExceptionBase 101 | { 102 | /// 103 | /// Creates a new 104 | /// 105 | /// 106 | /// 107 | /// 108 | /// 109 | public MethodNotAllowedApiException(string message = "Method not allowed", string? errorType = null, ApiExceptionPayload? payload = null, Exception? innerException = null) 110 | : base(message, ApiStatusCode.MethodNotAllowed, errorType, payload, innerException) 111 | { } 112 | } 113 | 114 | /// 115 | /// Represents a no content API exception. 116 | /// 117 | public class NoContentApiException : ApiExceptionBase 118 | { 119 | /// 120 | /// Creates a new 121 | /// 122 | /// 123 | /// 124 | /// 125 | /// 126 | public NoContentApiException(string message = "No Content", string? errorType = null, ApiExceptionPayload? payload = null, Exception? innerException = null) 127 | : base(message, ApiStatusCode.NoContent, errorType, payload, innerException) 128 | { } 129 | } 130 | 131 | /// 132 | /// Represents a not found API exception. 133 | /// 134 | public class NotFoundApiException : ApiExceptionBase 135 | { 136 | /// 137 | /// Creates a new 138 | /// 139 | /// 140 | /// 141 | /// 142 | /// 143 | public NotFoundApiException(string message = "Not found", string? errorType = null, ApiExceptionPayload? payload = null, Exception? innerException = null) 144 | : base(message, ApiStatusCode.NotFound, errorType, payload, innerException) 145 | { } 146 | } 147 | 148 | /// 149 | /// Represents an unauthorized API exception. 150 | /// 151 | public class UnauthorizedApiException : ApiExceptionBase 152 | { 153 | /// 154 | /// Creates a new 155 | /// 156 | /// 157 | /// 158 | /// 159 | /// 160 | public UnauthorizedApiException(string message = "Unauthorized", string? errorType = null, ApiExceptionPayload? payload = null, Exception? innerException = null) 161 | : base(message, ApiStatusCode.Unauthorized, errorType, payload, innerException) 162 | { } 163 | } -------------------------------------------------------------------------------- /tests/BitzArt.ApiExceptions.AspNetCore.Tests/BitzArt.ApiExceptions.AspNetCore.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | false 9 | 10 | BitzArt.ApiExceptions 11 | 12 | 13 | 14 | 15 | 16 | 17 | runtime; build; native; contentfiles; analyzers; buildtransitive 18 | all 19 | 20 | 21 | runtime; build; native; contentfiles; analyzers; buildtransitive 22 | all 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /tests/BitzArt.ApiExceptions.AspNetCore.Tests/ProblemDetailsTests.cs: -------------------------------------------------------------------------------- 1 | namespace BitzArt.ApiExceptions 2 | { 3 | public class ProblemDetailsTests 4 | { 5 | [Fact] 6 | public void Ctor_FromException_ReturnsProper() 7 | { 8 | var msg = "some text here"; 9 | var exception = new Exception(msg); 10 | var pd = new ProblemDetails(exception); 11 | 12 | Assert.Equal(pd.Title, msg); 13 | 14 | Assert.Null(pd.ErrorType); 15 | Assert.Null(pd.Detail); 16 | Assert.Null(pd.Instance); 17 | 18 | Assert.False(pd.Extensions.Any()); 19 | } 20 | 21 | [Fact] 22 | public void Ctor_FromApiException_ReturnsProper() 23 | { 24 | var msg = "some text here"; 25 | var exception = new CustomApiException(msg); 26 | var pd = new ProblemDetails(exception); 27 | 28 | Assert.Equal(pd.Title, msg); 29 | 30 | Assert.Null(pd.ErrorType); 31 | Assert.Null(pd.Detail); 32 | Assert.Null(pd.Instance); 33 | 34 | Assert.False(pd.Extensions.Any()); 35 | } 36 | 37 | [Fact] 38 | public void CtorFromExceptionWithInnerException_NotIncludeInner_ReturnsProper() 39 | { 40 | var innerLevel3 = new Exception("Level 3"); 41 | var innerLevel2 = new Exception("Level 2", innerLevel3); 42 | var innerLevel1 = new Exception("Level 1", innerLevel2); 43 | var outter = new Exception("Outter", innerLevel1); 44 | 45 | var problemDetails = new ProblemDetails(outter, addInner: false); 46 | 47 | Assert.False(problemDetails.Extensions.Any()); 48 | } 49 | 50 | [Fact] 51 | public void CtorFromExceptionWithInnerException_IncludeInner_ReturnsProper() 52 | { 53 | var innerLevel3 = new Exception("Level 3"); 54 | var innerLevel2 = new Exception("Level 2", innerLevel3); 55 | var innerLevel1 = new Exception("Level 1", innerLevel2); 56 | var outter = new Exception("Outter", innerLevel1); 57 | 58 | var problemDetails = new ProblemDetails(outter, addInner: true); 59 | 60 | Assert.True(problemDetails.Extensions.Any()); 61 | Assert.Contains(problemDetails.Extensions, x => x.Key == "inner"); 62 | 63 | var level1 = (problemDetails.Extensions.First().Value as IDictionary)!; 64 | Assert.True(level1.Any()); 65 | Assert.Contains(level1, x => x.Key == "title"); 66 | Assert.Contains(level1, x => x.Key == "inner"); 67 | 68 | var level2 = (level1.First(x => x.Key == "inner").Value as IDictionary)!; 69 | Assert.True(level2.Any()); 70 | Assert.Contains(level2, x => x.Key == "title"); 71 | Assert.Contains(level2, x => x.Key == "inner"); 72 | 73 | var level3 = (level2.First(x => x.Key == "inner").Value as IDictionary)!; 74 | Assert.True(level3.Any()); 75 | Assert.Contains(level3, x => x.Key == "title"); 76 | 77 | Assert.DoesNotContain(level3, x => x.Key == "inner"); 78 | } 79 | 80 | [Fact] 81 | public void AddErrorType_OnApiException_EndsUpInProblemDetails() 82 | { 83 | var exception = new CustomApiException(); 84 | var errorType = "some error type here"; 85 | exception.ErrorType = errorType; 86 | var pd = new ProblemDetails(exception); 87 | 88 | Assert.Equal(pd.ErrorType, errorType); 89 | 90 | Assert.Null(pd.Detail); 91 | Assert.Null(pd.Instance); 92 | 93 | Assert.False(pd.Extensions.Any()); 94 | } 95 | 96 | [Fact] 97 | public void AddDetail_OnApiException_EndsUpInProblemDetails() 98 | { 99 | var exception = new CustomApiException(); 100 | var detail = "some detail here"; 101 | exception.Detail = detail; 102 | var pd = new ProblemDetails(exception); 103 | 104 | Assert.Equal(pd.Detail, detail); 105 | 106 | Assert.Null(pd.ErrorType); 107 | Assert.Null(pd.Instance); 108 | 109 | Assert.False(pd.Extensions.Any()); 110 | } 111 | 112 | [Fact] 113 | public void AddInstance_OnApiException_EndsUpInProblemDetails() 114 | { 115 | var exception = new CustomApiException(); 116 | var instance = "some instance here"; 117 | exception.Instance = instance; 118 | var pd = new ProblemDetails(exception); 119 | 120 | Assert.Equal(pd.Instance, instance); 121 | 122 | Assert.Null(pd.ErrorType); 123 | Assert.Null(pd.Detail); 124 | 125 | Assert.False(pd.Extensions.Any()); 126 | } 127 | 128 | [Theory] 129 | [InlineData("someKey", "someValue")] 130 | [InlineData("integer", 123)] 131 | public void AddExtensions_OnApiException_EndsUpInProblemDetails(string key, object value) 132 | { 133 | var exception = new CustomApiException(); 134 | exception.Payload.AddData(key, value); 135 | var pd = new ProblemDetails(exception); 136 | 137 | Assert.Contains(pd.Extensions, x => x.Key == key && x.Value == value); 138 | } 139 | 140 | private class CustomApiException : ApiExceptionBase 141 | { 142 | public CustomApiException() : base() { } 143 | public CustomApiException(string message) : base(message) { } 144 | } 145 | } 146 | } -------------------------------------------------------------------------------- /tests/BitzArt.ApiExceptions.OpenTelemetry.Tests/BitzArt.ApiExceptions.OpenTelemetry.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | false 9 | 10 | BitzArt.ApiExceptions 11 | 12 | 13 | 14 | 15 | 16 | 17 | runtime; build; native; contentfiles; analyzers; buildtransitive 18 | all 19 | 20 | 21 | runtime; build; native; contentfiles; analyzers; buildtransitive 22 | all 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /tests/BitzArt.ApiExceptions.OpenTelemetry.Tests/Tests.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.ExceptionServices; 2 | 3 | namespace BitzArt.ApiExceptions; 4 | 5 | public class Tests 6 | { 7 | [Fact] 8 | public void ApiException_OnCreate_EventRaised() 9 | { 10 | var raised = false; 11 | AppDomain.CurrentDomain.FirstChanceException += EventHandler; 12 | 13 | void EventHandler(object? sender, FirstChanceExceptionEventArgs e) 14 | => raised = true; 15 | 16 | var exception1 = new Exception("test exception"); 17 | 18 | Assert.False(raised); 19 | 20 | try { throw exception1; } 21 | catch (Exception) { } 22 | 23 | Assert.True(raised); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /tests/BitzArt.ApiExceptions.Tests/ApiExceptionBaseTests.cs: -------------------------------------------------------------------------------- 1 | namespace BitzArt.ApiExceptions.Tests; 2 | 3 | public class ApiExceptionBaseTests 4 | { 5 | [Fact] 6 | public void Ctor_Default_ConstructsProperly() 7 | { 8 | var sut = new Sut(); 9 | Assert.Equal("Unexpected Error", sut.Message); 10 | Assert.Equal((int)ApiStatusCode.Error, sut.StatusCode); 11 | } 12 | 13 | [Theory] 14 | [InlineData("error message", ApiStatusCode.Error)] 15 | [InlineData("error message", (ApiStatusCode)12345)] 16 | [InlineData("this is a longer error message this is a longer error message this is a longer error message", ApiStatusCode.Error)] 17 | [InlineData("1234567890!@#$%^&*()[]", ApiStatusCode.Error)] 18 | public void Ctor_WithParams_ConstructsProperly(string msg, ApiStatusCode statusCode) 19 | { 20 | var sut = new Sut(msg, statusCode); 21 | Assert.Equal(msg, sut.Message); 22 | Assert.Equal((int)statusCode, sut.StatusCode); 23 | } 24 | 25 | [Fact] 26 | public void Ctor_WithErrorType_AddsErrorTypeToPayload() 27 | { 28 | var errorType = "some error type"; 29 | var sut = new InternalErrorApiException("some message", errorType); 30 | Assert.Equal(errorType, sut.ErrorType); 31 | } 32 | 33 | private class Sut : ApiExceptionBase 34 | { 35 | public Sut() : base() { } 36 | public Sut(string message, ApiStatusCode statusCode = ApiStatusCode.Error) 37 | : base(message, statusCode) { } 38 | } 39 | } -------------------------------------------------------------------------------- /tests/BitzArt.ApiExceptions.Tests/ApiExceptionPayloadTests.cs: -------------------------------------------------------------------------------- 1 | namespace BitzArt.ApiExceptions.Tests; 2 | 3 | public class ApiExceptionPayloadTests 4 | { 5 | [Theory] 6 | [InlineData("SomeKey", "SomeValue")] 7 | [InlineData("Integer", 12345)] 8 | public void Add_WithKeyAndValue_AddsToExtensions(string key, object value) 9 | { 10 | var sut = new Sut(); 11 | sut.Payload.AddData(key, value); 12 | 13 | var added = sut.Payload.Data.Single(); 14 | Assert.True(added.Key == key); 15 | Assert.True(added.Value == value); 16 | } 17 | 18 | [Fact] 19 | public void Add_WithComplexObject_AddsToExtensions() 20 | { 21 | var sut = new Sut(); 22 | 23 | var inner = new { a = "something", b = "something else" }; 24 | var complex = new { outter = "this", inner }; 25 | 26 | sut.Payload.AddData(complex); 27 | 28 | Assert.Contains(sut.Payload.Data, x => x.Key == "outter"); 29 | Assert.Contains(sut.Payload.Data, x => x.Key == "inner"); 30 | } 31 | 32 | private class Sut : ApiExceptionBase 33 | { 34 | public Sut() : base() { } 35 | } 36 | } -------------------------------------------------------------------------------- /tests/BitzArt.ApiExceptions.Tests/BitzArt.ApiExceptions.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | false 9 | 10 | 11 | 12 | 13 | 14 | 15 | runtime; build; native; contentfiles; analyzers; buildtransitive 16 | all 17 | 18 | 19 | runtime; build; native; contentfiles; analyzers; buildtransitive 20 | all 21 | 22 | 23 | 24 | 25 | 26 | 27 | --------------------------------------------------------------------------------