Beispiel #1
0
        /// <summary>
        /// Sets up a custom exception handler in the application's pipeline.
        /// </summary>
        /// <param name="app">A class which allows configuration of the application's request pipeline.</param>
        protected void SetupExceptionHandler(IApplicationBuilder app)
        {
            // As per https://docs.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-5.0#exception-handler-lambda
            app.UseExceptionHandler(errorApp =>
            {
                var exceptionToHttpStatusCodeConverter          = (ExceptionToHttpStatusCodeConverter)app.ApplicationServices.GetService(typeof(ExceptionToHttpStatusCodeConverter));
                var exceptionToHttpInternalServerErrorConverter = (ExceptionToHttpInternalServerErrorConverter)app.ApplicationServices.GetService(typeof(ExceptionToHttpInternalServerErrorConverter));

                errorApp.Run(async context =>
                {
                    // Get the exception
                    var exceptionHandlerPathFeature = context.Features.Get <IExceptionHandlerPathFeature>();
                    Exception exception             = exceptionHandlerPathFeature.Error;

                    if (exception != null)
                    {
                        context.Response.ContentType = jsonHttpContentType;
                        context.Response.StatusCode  = (Int32)exceptionToHttpStatusCodeConverter.Convert(exception);
                        HttpInternalServerError httpInternalServerError = exceptionToHttpInternalServerErrorConverter.Convert(exception);
                        var serializer = new HttpInternalServerErrorJsonSerializer();
                        await context.Response.WriteAsync(serializer.Serialize(httpInternalServerError).ToString());
                    }
                    else
                    {
                        // Not sure if this situation can arise, but will leave this handler in while testing
                        throw new Exception("'exceptionHandlerPathFeature.Error' was null whilst handling exception.");
                    }
                });
            });
        }
Beispiel #2
0
 protected void SetUp()
 {
     testHttpInternalServerErrorJsonSerializer = new HttpInternalServerErrorJsonSerializer();
 }