Created
February 15, 2017 23:07
-
-
Save gravity00/2abda8cf352236cfc620be33b72c0200 to your computer and use it in GitHub Desktop.
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
| public class GlobalExceptionFilter : IExceptionFilter | |
| { | |
| private readonly ILogger<ExampleExceptionFilter> _logger; | |
| public ExampleExceptionFilter(ILogger<ExampleExceptionFilter> logger) | |
| { | |
| _logger = logger; | |
| } | |
| public void OnException(ExceptionContext context) | |
| { | |
| int statusCode; | |
| string message; | |
| Dictionary<string, string> modelState; | |
| var ex = context.Exception; | |
| var validationEx = ex as ValidationException; | |
| if (validationEx == null) | |
| { | |
| var notImplementedEx = ex as NotImplementedException; | |
| if (notImplementedEx == null) | |
| { | |
| var timeoutEx = ex as TimeoutException; | |
| if (timeoutEx == null) | |
| { | |
| _logger.LogError(0, ex, "Exception unknown has been thrown"); | |
| statusCode = (int) HttpStatusCode.InternalServerError; | |
| message = "Connection failed to some internal service"; | |
| } | |
| else | |
| { | |
| _logger.LogError(0, timeoutEx, "TimeoutException has been thrown"); | |
| statusCode = (int) HttpStatusCode.GatewayTimeout; | |
| message = "Connection failed to some internal service"; | |
| } | |
| } | |
| else | |
| { | |
| _logger.LogCritical(0, notImplementedEx, "NotImplementedException has been thrown"); | |
| statusCode = (int) HttpStatusCode.NotImplemented; | |
| message = "The action is not implemented"; | |
| } | |
| modelState = new Dictionary<string, string>(0); | |
| } | |
| else | |
| { | |
| _logger.LogWarning(0, validationEx, "ValidationException has been thrown"); | |
| statusCode = 422; | |
| message = "The provided entity has invalid data"; | |
| modelState = validationEx.ModelState; | |
| } | |
| context.HttpContext.Response.StatusCode = statusCode; | |
| context.Result = new JsonResult(new | |
| { | |
| Code = statusCode, | |
| Message = message, | |
| ModelState = modelState | |
| }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment