├── .gitattributes ├── .gitignore ├── .travis.yml ├── AspNetCore.FriendlyExceptions.sln ├── LICENSE ├── README.md └── src ├── AspNetCore.FriendlyExceptions.csproj ├── Extensions ├── ApplicationBuilderExtensions.cs ├── HttpContextExtensions.cs └── ServiceCollectionExtensions.cs ├── FriendlyExceptionAttribute.cs ├── FriendlyExceptionsMiddleware.cs ├── Options └── TranformOptions.cs └── Transforms ├── Interfaces ├── ITransform.cs ├── ITransformTo.cs ├── ITransformsCollection.cs └── ITransformsMap.cs └── TransformsCollectionBuilder.cs /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | project.fragment.lock.json 46 | artifacts/ 47 | 48 | *_i.c 49 | *_p.c 50 | *_i.h 51 | *.ilk 52 | *.meta 53 | *.obj 54 | *.pch 55 | *.pdb 56 | *.pgc 57 | *.pgd 58 | *.rsp 59 | *.sbr 60 | *.tlb 61 | *.tli 62 | *.tlh 63 | *.tmp 64 | *.tmp_proj 65 | *.log 66 | *.vspscc 67 | *.vssscc 68 | .builds 69 | *.pidb 70 | *.svclog 71 | *.scc 72 | 73 | # Chutzpah Test files 74 | _Chutzpah* 75 | 76 | # Visual C++ cache files 77 | ipch/ 78 | *.aps 79 | *.ncb 80 | *.opendb 81 | *.opensdf 82 | *.sdf 83 | *.cachefile 84 | *.VC.db 85 | *.VC.VC.opendb 86 | 87 | # Visual Studio profiler 88 | *.psess 89 | *.vsp 90 | *.vspx 91 | *.sap 92 | 93 | # TFS 2012 Local Workspace 94 | $tf/ 95 | 96 | # Guidance Automation Toolkit 97 | *.gpState 98 | 99 | # ReSharper is a .NET coding add-in 100 | _ReSharper*/ 101 | *.[Rr]e[Ss]harper 102 | *.DotSettings.user 103 | 104 | # JustCode is a .NET coding add-in 105 | .JustCode 106 | 107 | # TeamCity is a build add-in 108 | _TeamCity* 109 | 110 | # DotCover is a Code Coverage Tool 111 | *.dotCover 112 | 113 | # NCrunch 114 | _NCrunch_* 115 | .*crunch*.local.xml 116 | nCrunchTemp_* 117 | 118 | # MightyMoose 119 | *.mm.* 120 | AutoTest.Net/ 121 | 122 | # Web workbench (sass) 123 | .sass-cache/ 124 | 125 | # Installshield output folder 126 | [Ee]xpress/ 127 | 128 | # DocProject is a documentation generator add-in 129 | DocProject/buildhelp/ 130 | DocProject/Help/*.HxT 131 | DocProject/Help/*.HxC 132 | DocProject/Help/*.hhc 133 | DocProject/Help/*.hhk 134 | DocProject/Help/*.hhp 135 | DocProject/Help/Html2 136 | DocProject/Help/html 137 | 138 | # Click-Once directory 139 | publish/ 140 | 141 | # Publish Web Output 142 | *.[Pp]ublish.xml 143 | *.azurePubxml 144 | # TODO: Comment the next line if you want to checkin your web deploy settings 145 | # but database connection strings (with potential passwords) will be unencrypted 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 150 | # checkin your Azure Web App publish settings, but sensitive information contained 151 | # in these scripts will be unencrypted 152 | PublishScripts/ 153 | 154 | # NuGet Packages 155 | *.nupkg 156 | # The packages folder can be ignored because of Package Restore 157 | **/packages/* 158 | # except build/, which is used as an MSBuild target. 159 | !**/packages/build/ 160 | # Uncomment if necessary however generally it will be regenerated when needed 161 | #!**/packages/repositories.config 162 | # NuGet v3's project.json files produces more ignoreable files 163 | *.nuget.props 164 | *.nuget.targets 165 | 166 | # Microsoft Azure Build Output 167 | csx/ 168 | *.build.csdef 169 | 170 | # Microsoft Azure Emulator 171 | ecf/ 172 | rcf/ 173 | 174 | # Windows Store app package directories and files 175 | AppPackages/ 176 | BundleArtifacts/ 177 | Package.StoreAssociation.xml 178 | _pkginfo.txt 179 | 180 | # Visual Studio cache files 181 | # files ending in .cache can be ignored 182 | *.[Cc]ache 183 | # but keep track of directories ending in .cache 184 | !*.[Cc]ache/ 185 | 186 | # Others 187 | ClientBin/ 188 | ~$* 189 | *~ 190 | *.dbmdl 191 | *.dbproj.schemaview 192 | *.jfm 193 | *.pfx 194 | *.publishsettings 195 | node_modules/ 196 | orleans.codegen.cs 197 | 198 | # Since there are multiple workflows, uncomment next line to ignore bower_components 199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 200 | #bower_components/ 201 | 202 | # RIA/Silverlight projects 203 | Generated_Code/ 204 | 205 | # Backup & report files from converting an old project file 206 | # to a newer Visual Studio version. Backup files are not needed, 207 | # because we have git ;-) 208 | _UpgradeReport_Files/ 209 | Backup*/ 210 | UpgradeLog*.XML 211 | UpgradeLog*.htm 212 | 213 | # SQL Server files 214 | *.mdf 215 | *.ldf 216 | 217 | # Business Intelligence projects 218 | *.rdl.data 219 | *.bim.layout 220 | *.bim_*.settings 221 | 222 | # Microsoft Fakes 223 | FakesAssemblies/ 224 | 225 | # GhostDoc plugin setting file 226 | *.GhostDoc.xml 227 | 228 | # Node.js Tools for Visual Studio 229 | .ntvs_analysis.dat 230 | 231 | # Visual Studio 6 build log 232 | *.plg 233 | 234 | # Visual Studio 6 workspace options file 235 | *.opt 236 | 237 | # Visual Studio LightSwitch build output 238 | **/*.HTMLClient/GeneratedArtifacts 239 | **/*.DesktopClient/GeneratedArtifacts 240 | **/*.DesktopClient/ModelManifest.xml 241 | **/*.Server/GeneratedArtifacts 242 | **/*.Server/ModelManifest.xml 243 | _Pvt_Extensions 244 | 245 | # Paket dependency manager 246 | .paket/paket.exe 247 | paket-files/ 248 | 249 | # FAKE - F# Make 250 | .fake/ 251 | 252 | # JetBrains Rider 253 | .idea/ 254 | *.sln.iml 255 | 256 | # CodeRush 257 | .cr/ 258 | 259 | # Python Tools for Visual Studio (PTVS) 260 | __pycache__/ 261 | *.pyc -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: csharp 2 | mono: none 3 | dotnet: 1.1.5 4 | sudo: required 5 | dist: trusty 6 | 7 | install: 8 | - dotnet restore 9 | 10 | script: 11 | - dotnet pack --configuration release --output nupkgs --version-suffix .$TRAVIS_BUILD_NUMBER 12 | - dotnet nuget push ./src/nupkgs/AspNetCore.FriendlyExceptions.*.nupkg --api-key $NUGET_API_KEY --source $NUGET_SOURCE 13 | -------------------------------------------------------------------------------- /AspNetCore.FriendlyExceptions.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26430.14 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AspNetCore.FriendlyExceptions", "src\AspNetCore.FriendlyExceptions.csproj", "{8C3234C7-7B9A-41E4-B2BE-253577500A81}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {8C3234C7-7B9A-41E4-B2BE-253577500A81}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {8C3234C7-7B9A-41E4-B2BE-253577500A81}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {8C3234C7-7B9A-41E4-B2BE-253577500A81}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {8C3234C7-7B9A-41E4-B2BE-253577500A81}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | EndGlobal 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015-2017 Anders Åberg, Andriy S'omak 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 | # ASP.NET Core Friendly Exceptions Filter and Middleware [![Build Status](https://travis-ci.org/semack/AspNetCore.FriendlyExceptions.svg?branch=master)](https://travis-ci.org/semack/AspNetCore.FriendlyExceptions) 2 | 3 | A filter and middleware that can translate exceptions into nice http resonses. This allows you to throw meaningfull exceptions from your framework, business code or other middlewares and translate the exceptions to nice and friendly http responses. 4 | 5 | ## Authors 6 | This code based on [Owin Friendly Exceptions Middleware](https://github.com/abergs/OwinFriendlyExceptions) created by [Anders Åberg](https://github.com/abergs) and has been adapted for ASP.NET Core usage by [Andriy S'omak](https://github.com/semack). 7 | 8 | ## Installation 9 | Before using of the library [Nuget Package](https://www.nuget.org/packages/AspNetCore.FriendlyExceptions/) must be installed. 10 | 11 | `Install-Package AspNetCore.FriendlyExceptions` 12 | 13 | ## Examples of usage 14 | There are a two ways of using of the library: using ExceptionFilter or registering Midlleware. You can choose any of them. 15 | 16 | ### Configuration 17 | Add transformation rules to the Startup.cs file. 18 | ```cs 19 | public void ConfigureServices(IServiceCollection services) 20 | { 21 | ... 22 | services.AddFriendlyExceptionsTransforms(options => 23 | { 24 | options.Transforms = TransformsCollectionBuilder.Begin() 25 | 26 | .Map() 27 | .To(HttpStatusCode.BadRequest, "This is the reasonphrase", 28 | ex => "And this is the response content: " + ex.Message) 29 | 30 | .Map() 31 | .To(HttpStatusCode.NoContent, "Bucket is emtpy", ex => string.Format("Inner details: {0}", ex.Message)) 32 | 33 | .Map() 34 | .To(HttpStatusCode.NotFound, "Entity does not exist", ex => ex.Message) 35 | 36 | .Map() 37 | .To(HttpStatusCode.Unauthorized, "Invalid authentication", ex => ex.Message) 38 | 39 | .Map() 40 | .To(HttpStatusCode.Forbidden, "Forbidden", ex => ex.Message) 41 | 42 | // Map all other exceptions if needed. 43 | // Also it would be useful if you want to map exception to a known model. 44 | .MapAllOthers() 45 | .To(HttpStatusCode.InternalServerError, "Internal Server Error", ex => ex.Message) 46 | 47 | .Done(); 48 | }); 49 | ... 50 | } 51 | ``` 52 | 53 | By default, FriendlyExceptions sets the response Content-Type to `text/plain`. To use a different type: 54 | ```cs 55 | .Map() 56 | .To(HttpStatusCode.BadRequest, "This exception is json", 57 | ex => JsonConvert.SerializeObject(ex.Message), "application/json") 58 | ``` 59 | 60 | ### Using filter 61 | Register ExceptionFilter. 62 | ```cs 63 | public void ConfigureServices(IServiceCollection services) 64 | { 65 | ... 66 | services.AddMvc() 67 | .AddMvcOptions(s => s.Filters.Add(typeof(FriendlyExceptionAttribute))) 68 | ... 69 | } 70 | ``` 71 | Add filter attribute to the Controller. 72 | ```cs 73 | [Produces("application/json")] 74 | [FriendlyException] 75 | public class AccountController : Controller 76 | { 77 | ... 78 | ``` 79 | ### Using Middleware 80 | In case you use middleware, the registration method must be at the top of list of all registrations. 81 | ```cs 82 | public void Configure(IApplicationBuilder app) 83 | { 84 | app.UseFriendlyExceptions(); 85 | ... 86 | } 87 | 88 | ``` 89 | 90 | ## Contribute 91 | Contributions are welcome. Just open an Issue or submit a PR. 92 | 93 | ## Contact 94 | You can reach me via my [email](mailto://semack@gmail.com) 95 | -------------------------------------------------------------------------------- /src/AspNetCore.FriendlyExceptions.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netcoreapp1.1 5 | AspNetCore.FriendlyExceptions 6 | abergs, semack 7 | ONLINICO 8 | AspNetCore.FriendlyExceptions 9 | 0.0.1$(VersionSuffix) 10 | AspNetCore.FriendlyExceptions 11 | AspNetCore.FriendlyExceptions 12 | False 13 | https://github.com/semack/AspNetCore.FriendlyExceptions/blob/master/LICENSE 14 | https://github.com/semack/AspNetCore.FriendlyExceptions 15 | https://github.com/semack/AspNetCore.FriendlyExceptions.git 16 | git 17 | middleware asp-net-core asp-net-core-web-api asp-net-core-mvc exception-handling 18 | Adeed possibility to use ExceptionFilter without callingTypeFilter() 19 | 0.0.1$(VersionSuffix) 20 | Copyright ©2015-2017 Anders Åberg, Andriy S'omak 21 | ASP.NET Core Friendly Exceptions Filter and Middleware. 22 | A filter and middleware that can translate exceptions into nice http resonses. This allows you to throw meaningfull exceptions from your framework, business code or other middlewares and translate the exceptions to nice and friendly http responses. 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /src/Extensions/ApplicationBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | 3 | namespace AspNetCore.FriendlyExceptions.Extensions 4 | { 5 | public static class ApplicationBuilderExtensions 6 | { 7 | public static void UseFriendlyExceptions(this IApplicationBuilder appBuilder) 8 | { 9 | appBuilder.UseMiddleware(); 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /src/Extensions/HttpContextExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | using System.Threading.Tasks; 4 | using AspNetCore.FriendlyExceptions.Options; 5 | using Microsoft.AspNetCore.Http; 6 | using Microsoft.AspNetCore.Http.Features; 7 | using Microsoft.Extensions.Options; 8 | 9 | namespace AspNetCore.FriendlyExceptions.Extensions 10 | { 11 | internal static class HttpContextExtensions 12 | { 13 | internal static async Task HandleExceptionAsync(this HttpContext context, 14 | IOptions options, 15 | Exception exception) 16 | { 17 | var transformer = options.Value.Transforms?.FindTransform(exception); 18 | if (transformer == null) 19 | throw exception; 20 | 21 | var content = transformer.GetContent(exception); 22 | 23 | context.Response.ContentType = transformer.ContentType; 24 | context.Response.StatusCode = (int) transformer.StatusCode; 25 | context.Response.HttpContext.Features.Get().ReasonPhrase = transformer.ReasonPhrase; 26 | context.Response.ContentLength = Encoding.UTF8.GetByteCount(content); 27 | await context.Response.WriteAsync(content); 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /src/Extensions/ServiceCollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using AspNetCore.FriendlyExceptions.Options; 3 | using Microsoft.Extensions.DependencyInjection; 4 | 5 | namespace AspNetCore.FriendlyExceptions.Extensions 6 | { 7 | public static class ServiceCollectionExtensions 8 | { 9 | public static void AddFriendlyExceptionsTransforms(this IServiceCollection services, 10 | Action setupAction) 11 | { 12 | services.Configure(setupAction); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /src/FriendlyExceptionAttribute.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using AspNetCore.FriendlyExceptions.Extensions; 3 | using AspNetCore.FriendlyExceptions.Options; 4 | using Microsoft.AspNetCore.Mvc.Filters; 5 | using Microsoft.Extensions.Options; 6 | 7 | namespace AspNetCore.FriendlyExceptions 8 | { 9 | public class FriendlyExceptionAttribute : ExceptionFilterAttribute 10 | { 11 | public override async Task OnExceptionAsync(ExceptionContext context) 12 | { 13 | if (context.Exception != null) 14 | { 15 | var options = context.HttpContext.RequestServices.GetService(typeof(IOptions)) as IOptions; 16 | await context.HttpContext.HandleExceptionAsync(options, context.Exception); 17 | context.ExceptionHandled = true; 18 | } 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /src/FriendlyExceptionsMiddleware.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | using AspNetCore.FriendlyExceptions.Extensions; 4 | using AspNetCore.FriendlyExceptions.Options; 5 | using Microsoft.AspNetCore.Http; 6 | using Microsoft.Extensions.Options; 7 | 8 | namespace AspNetCore.FriendlyExceptions 9 | { 10 | internal class FriendlyExceptionsMiddleware 11 | { 12 | private readonly RequestDelegate _next; 13 | private readonly IOptions _options; 14 | 15 | public FriendlyExceptionsMiddleware(RequestDelegate next, 16 | IOptions options) 17 | { 18 | _next = next; 19 | _options = options; 20 | } 21 | 22 | public async Task Invoke(HttpContext context) 23 | { 24 | try 25 | { 26 | await _next(context); 27 | } 28 | catch (Exception exception) 29 | { 30 | await context.HandleExceptionAsync(_options, exception); 31 | } 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /src/Options/TranformOptions.cs: -------------------------------------------------------------------------------- 1 | using AspNetCore.FriendlyExceptions.Transforms.Interfaces; 2 | 3 | namespace AspNetCore.FriendlyExceptions.Options 4 | { 5 | public class TranformOptions 6 | { 7 | public virtual ITransformsCollection Transforms { get; set; } 8 | } 9 | } -------------------------------------------------------------------------------- /src/Transforms/Interfaces/ITransform.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | 4 | namespace AspNetCore.FriendlyExceptions.Transforms.Interfaces 5 | { 6 | public interface ITransform 7 | { 8 | HttpStatusCode StatusCode { get; } 9 | string ReasonPhrase { get; } 10 | string ContentType { get; } 11 | string GetContent(Exception ex); 12 | bool CanHandle(T2 ex) where T2 : Exception; 13 | } 14 | } -------------------------------------------------------------------------------- /src/Transforms/Interfaces/ITransformTo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | 4 | namespace AspNetCore.FriendlyExceptions.Transforms.Interfaces 5 | { 6 | public interface ITransformTo 7 | { 8 | ITransformsMap To(HttpStatusCode statusCode, string reasonPhrase, 9 | Func contentGenerator, string contentType = "text/plain"); 10 | } 11 | } -------------------------------------------------------------------------------- /src/Transforms/Interfaces/ITransformsCollection.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace AspNetCore.FriendlyExceptions.Transforms.Interfaces 4 | { 5 | public interface ITransformsCollection 6 | { 7 | ITransform FindTransform(Exception exception); 8 | } 9 | } -------------------------------------------------------------------------------- /src/Transforms/Interfaces/ITransformsMap.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace AspNetCore.FriendlyExceptions.Transforms.Interfaces 4 | { 5 | public interface ITransformsMap 6 | { 7 | ITransformTo Map() where T : Exception; 8 | ITransformTo Map(Func matcher); 9 | ITransformTo MapAllOthers(); 10 | ITransformsCollection Done(); 11 | } 12 | } -------------------------------------------------------------------------------- /src/Transforms/TransformsCollectionBuilder.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net; 5 | using AspNetCore.FriendlyExceptions.Transforms.Interfaces; 6 | 7 | namespace AspNetCore.FriendlyExceptions.Transforms 8 | { 9 | public class TransformsCollectionBuilder : ITransformsMap, ITransformsCollection 10 | { 11 | private readonly List _transforms = new List(); 12 | 13 | private TransformsCollectionBuilder() 14 | { 15 | } 16 | 17 | public ITransform FindTransform(Exception exception) 18 | { 19 | var handler = _transforms.FirstOrDefault(x => x.CanHandle(exception)); 20 | return handler; 21 | } 22 | 23 | public ITransformTo Map() where T : Exception 24 | { 25 | var transform = new Transform(this); 26 | return transform; 27 | } 28 | 29 | public ITransformTo Map(Func matching) 30 | { 31 | var transform = new Transform(this, matching); 32 | return transform; 33 | } 34 | 35 | public ITransformTo MapAllOthers() 36 | { 37 | return Map(); 38 | } 39 | 40 | public ITransformsCollection Done() 41 | { 42 | return this; 43 | } 44 | 45 | public static ITransformsMap Begin() 46 | { 47 | return new TransformsCollectionBuilder(); 48 | } 49 | 50 | 51 | private class Transform : ITransformTo, ITransform where T : Exception 52 | { 53 | private readonly Func _matcher; 54 | private readonly TransformsCollectionBuilder _transformsCollectionBuilder; 55 | private Func _contentGenerator; 56 | 57 | public Transform(TransformsCollectionBuilder transformsCollectionBuilder) 58 | : this(transformsCollectionBuilder, ex => ex.GetType() == typeof(T)) 59 | { 60 | } 61 | 62 | public Transform(TransformsCollectionBuilder transformsCollectionBuilder, Func matching) 63 | { 64 | _transformsCollectionBuilder = transformsCollectionBuilder; 65 | _matcher = matching; 66 | } 67 | 68 | public string GetContent(Exception ex2) 69 | { 70 | var ex = (T) ex2; 71 | return _contentGenerator(ex); 72 | } 73 | 74 | public bool CanHandle(T2 ex) where T2 : Exception 75 | { 76 | var result = _matcher(ex); 77 | if (!result) 78 | result = _matcher(new Exception()); 79 | return result; 80 | } 81 | 82 | public string ContentType { get; private set; } 83 | 84 | public HttpStatusCode StatusCode { get; private set; } 85 | public string ReasonPhrase { get; private set; } 86 | 87 | public ITransformsMap To(HttpStatusCode statusCode, string reasonPhrase, Func contentGenerator, 88 | string contentType = "text/plain") 89 | { 90 | StatusCode = statusCode; 91 | ReasonPhrase = reasonPhrase; 92 | ContentType = contentType; 93 | _contentGenerator = contentGenerator; 94 | _transformsCollectionBuilder._transforms.Add(this); 95 | return _transformsCollectionBuilder; 96 | } 97 | } 98 | } 99 | } --------------------------------------------------------------------------------