Created
June 16, 2014 12:13
-
-
Save jamescrowley/c82278bfd5c2a83f243c to your computer and use it in GitHub Desktop.
ErrorHandlingTests
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
namespace FundApps.DocumentGenerator.FeatureTests.OwinMiddleware | |
{ | |
using System; | |
using System.IO; | |
using System.Net; | |
using System.Net.Http; | |
using System.Threading.Tasks; | |
using FundApps.DocumentGenerator.Web.Infrastructure.Owin; | |
using Machine.Specifications; | |
using Microsoft.Owin; | |
using Microsoft.Owin.Testing; | |
using Owin; | |
public class ErrorHandlingTests | |
{ | |
protected static TestServer Server; | |
protected static HttpResponseMessage Response; | |
Establish context = () => Server = TestServer.Create(app => | |
app | |
.Use<GlobalExceptionHandlingMiddleware>() | |
.Use(CustomErrorPagesMiddleware.UseCustomErrorPages( | |
opts => | |
opts.WithErrorPage(500, async env => await new OwinResponse(env).WriteAsync("ServerError")))) | |
.Use<ThrowExceptionOnPathMiddleware>(new PathString("/ex"))); | |
class when_requesting_url_that_throws_exception { | |
Because of = () => Response = Server.HttpClient.GetAsync("/ex").Await(); | |
It should_set_500_status = () => Response.StatusCode.ShouldEqual(HttpStatusCode.InternalServerError); | |
It should_write_custom_error_page = () => Response.Content.ReadAsStringAsync().Result.ShouldContain("ServerError"); | |
} | |
Cleanup cleanup = () => Server.Dispose(); | |
} | |
class ThrowExceptionOnPathMiddleware : OwinMiddleware | |
{ | |
private readonly PathString throwExceptionOnPath; | |
public ThrowExceptionOnPathMiddleware(OwinMiddleware next, PathString throwExceptionOnPath) | |
: base(next) | |
{ | |
this.throwExceptionOnPath = throwExceptionOnPath; | |
} | |
public override Task Invoke(IOwinContext context) | |
{ | |
if (context.Request.Path == throwExceptionOnPath) | |
{ | |
throw new Exception("Unexpected middleware exception"); | |
} | |
return this.Next.Invoke(context); | |
} | |
} | |
class GlobalExceptionHandlingMiddleware : OwinMiddleware | |
{ | |
public GlobalExceptionHandlingMiddleware(OwinMiddleware next) | |
: base(next) | |
{ | |
} | |
public override async Task Invoke(IOwinContext context) | |
{ | |
try | |
{ | |
await Next.Invoke(context); | |
} | |
catch (Exception ex) | |
{ | |
OnError(context, ex.InnerException ?? ex); | |
} | |
} | |
private static void OnError(IOwinContext context, Exception ex) | |
{ | |
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment