Created
January 16, 2021 20:33
-
-
Save bruceharrison1984/f79849a1c55e1bd1c3eabbd2861bc3ec to your computer and use it in GitHub Desktop.
Example of how to implement global error handling in WebApi
This file contains hidden or 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 FluentValidation; | |
using System.Text.Json; | |
using System.Threading.Tasks; | |
using Logic.Exceptions; | |
using Microsoft.AspNetCore.Hosting; | |
using Microsoft.AspNetCore.Http; | |
using Microsoft.Extensions.Hosting; | |
using System.Linq; | |
using System.Collections.Generic; | |
using Microsoft.Data.SqlClient; | |
namespace Api.Middleware | |
{ | |
public class ErrorHandlingMiddleware : IMiddleware | |
{ | |
private readonly IWebHostEnvironment _env; | |
const string RESPONSE_CONTENT_TYPE = "application/json"; | |
public ErrorHandlingMiddleware(IWebHostEnvironment env) | |
{ | |
_env = env; | |
} | |
public async Task InvokeAsync(HttpContext context, RequestDelegate next) | |
{ | |
try | |
{ | |
await next(context); | |
} | |
catch (Exception ex) | |
{ | |
await HandleExceptionAsync(context, ex); | |
} | |
} | |
private async Task HandleExceptionAsync(HttpContext context, Exception exception) | |
{ | |
IEnumerable<string> message = new List<string> { exception.Message }; ; | |
int statusCode; | |
var stackTrace = _env.IsDevelopment() ? exception.StackTrace : string.Empty; | |
switch (exception) | |
{ | |
case ValidationException: | |
{ | |
var validationException = (ValidationException)exception; | |
message = validationException.Errors.Select(x => x.ErrorMessage); | |
statusCode = StatusCodes.Status400BadRequest; | |
break; | |
} | |
case NotFoundException: | |
{ | |
statusCode = StatusCodes.Status404NotFound; | |
break; | |
}; | |
case SqlException: | |
{ | |
statusCode = StatusCodes.Status500InternalServerError; | |
break; | |
}; | |
default: | |
{ | |
statusCode = StatusCodes.Status500InternalServerError; | |
break; | |
}; | |
} | |
var result = JsonSerializer.Serialize(new { error = message, stackTrace }); | |
context.Response.ContentType = RESPONSE_CONTENT_TYPE; | |
context.Response.StatusCode = statusCode; | |
await context.Response.WriteAsync(result); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment