Created
September 25, 2017 06:47
-
-
Save codehaks/210a06b924ba3b705c0ed3c4f0a7a900 to your computer and use it in GitHub Desktop.
Alternate pipeline for Error Handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Threading.Tasks; | |
using Microsoft.AspNetCore.Builder; | |
using Microsoft.AspNetCore.Diagnostics; | |
using Microsoft.AspNetCore.Hosting; | |
using Microsoft.AspNetCore.Http; | |
using Microsoft.Extensions.DependencyInjection; | |
namespace ErrorHandler3 { | |
public class Startup { | |
public void Configure (IApplicationBuilder app, IHostingEnvironment env) { | |
RequestDelegate handler = async (context) => { | |
var errorFeature = context.Features.Get<IExceptionHandlerFeature> (); | |
await context.Response.WriteAsync ("Error handler : " + Environment.NewLine + errorFeature.Error.Message); | |
}; | |
var errorHandlerOptions = new ExceptionHandlerOptions () { | |
ExceptionHandler = handler, | |
ExceptionHandlingPath = "/error" | |
}; | |
var subAppBuilder = app.New (); | |
Action<IApplicationBuilder>configure = (newApp) => { | |
newApp.Run (async (context) => { | |
await context.Response.WriteAsync ("Alternate reality : " + context.Request.Path); | |
}); | |
}; | |
var exceptionHandlerPipeline = subAppBuilder.Build (); | |
app.UseExceptionHandler (configure); | |
app.Use (async (context, next) => { | |
if (context.Request.Path == "/fail") { | |
throw new Exception ("Something went wrong !"); | |
} | |
await context.Response.WriteAsync ("No Errors" + Environment.NewLine); | |
await next.Invoke (); | |
}); | |
app.Run (async (context) => { | |
await context.Response.WriteAsync ("Page : " + context.Request.Path); | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In this code I'm trying to use Alternative pipepline capability of Error Handling middleware.
When something goes wrong aka Error, Error handling middleware starts a new Action . We can have different pipleline than main pipeline for managing Exeption Handling.