Skip to content

Instantly share code, notes, and snippets.

@shammelburg
Last active September 25, 2017 08:03
Show Gist options
  • Save shammelburg/13a238eab85e1347e278e500ceef9502 to your computer and use it in GitHub Desktop.
Save shammelburg/13a238eab85e1347e278e500ceef9502 to your computer and use it in GitHub Desktop.
ErrorHandlingMiddleware
public class ErrorHandlingMiddleware
{
private readonly RequestDelegate _next;
private readonly EmailSettings _settings;
public ErrorHandlingMiddleware(RequestDelegate next, IOptions<EmailSettings> settings)
{
_next = next;
_settings = settings.Value;
}
public async Task Invoke(HttpContext context)
{
// This will catch all exceptions if not caught anywhere else
try
{
await _next(context);
}
catch (SqlException ex)
{
EmailService.SendSqlException(ex, context.User.Identity.Name, _settings);
await HandleSqlExceptionAsync(context, ex);
}
catch (Exception ex)
{
EmailService.SendException(ex, context.User.Identity.Name, _settings);
await HandleExceptionAsync(context, ex);
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception ex)
{
var result = JsonConvert.SerializeObject(new
{
Type = "General Exception",
Exception = new
{
Message = ex.Message,
Inner = ex.InnerException
}
});
context.Response.ContentType = "application/json";
context.Response.StatusCode = 500;
return context.Response.WriteAsync(result);
}
private static Task HandleSqlExceptionAsync(HttpContext context, SqlException ex)
{
var errorList = new List<Object>();
for (int i = 0; i < ex.Errors.Count; i++)
{
errorList.Add(new
{
Message = ex.Errors[i].Message,
Procedure = ex.Errors[i].Procedure,
LineNumber = ex.Errors[i].LineNumber,
Source = ex.Errors[i].Source,
Server = ex.Errors[i].Server
});
}
var result = JsonConvert.SerializeObject(new
{
Type = "SQL Exception",
Exceptions = errorList
});
context.Response.ContentType = "application/json";
context.Response.StatusCode = 500;
return context.Response.WriteAsync(result);
}
}
public static class ErrorHandlingMiddlewareExtensions
{
public static IApplicationBuilder UseErrorHandlingMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<ErrorHandlingMiddleware>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment