Created
February 16, 2017 00:03
-
-
Save gravity00/e8605fcef19f538916c5dc2d28a8ce8b 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 ExampleExceptionFilter : IExceptionFilter | |
| { | |
| private readonly ILogger<ExampleExceptionFilter> _logger; | |
| public ExampleExceptionFilter(ILogger<ExampleExceptionFilter> logger) | |
| { | |
| _logger = logger; | |
| } | |
| public void OnException(ExceptionContext context) | |
| { | |
| var statusCode = 0; | |
| string message = null; | |
| var modelState = new Dictionary<string, string>(0); | |
| var result = | |
| Handling.Prepare() | |
| .On<ValidationException>(ex => | |
| { | |
| _logger.LogWarning(0, ex, "ValidationException has been thrown"); | |
| statusCode = 422; | |
| message = "The provided entity has invalid data"; | |
| modelState = ex.ModelState; | |
| }) | |
| .On<NotImplementedException>(ex => | |
| { | |
| _logger.LogCritical(0, ex, "NotImplementedException has been thrown"); | |
| statusCode = (int) HttpStatusCode.NotImplemented; | |
| message = "The action is not implemented"; | |
| }) | |
| .On<TimeoutException>(ex => | |
| { | |
| _logger.LogError(0, ex, "TimeoutException has been thrown"); | |
| statusCode = (int) HttpStatusCode.GatewayTimeout; | |
| message = "Connection failed to some internal service"; | |
| }) | |
| .Catch(context.Exception, throwIfNotHandled: false); | |
| if (!result.Handled) | |
| { | |
| _logger.LogError(0, context.Exception, "Exception unknown has been thrown"); | |
| statusCode = (int)HttpStatusCode.InternalServerError; | |
| message = "Connection failed to some internal service"; | |
| } | |
| 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