Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class GlobalExceptionFilter : IExceptionFilter, IDisposable
- {
- private readonly ILogger _logger;
- public GlobalExceptionFilter(ILoggerFactory logger)
- {
- if (logger == null)
- {
- throw new ArgumentNullException(nameof(logger));
- }
- this._logger = logger.CreateLogger("Global Exception Filter");
- }
- public void Dispose()
- {
- }
- public void OnException(ExceptionContext context)
- {
- Dictionary<string, string> data = new Dictionary<string, string>();
- HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
- String message = String.Empty;
- var ex = context.Exception;
- TypeSwitch.Do(ex,
- TypeSwitch.Case<ArgumentException>(() => { statusCode = HttpStatusCode.BadRequest; }),
- TypeSwitch.Case<ArgumentNullException>(() => { statusCode = HttpStatusCode.BadRequest; }),
- TypeSwitch.Case<ArgumentOutOfRangeException>(() => { statusCode = HttpStatusCode.BadRequest; }),
- TypeSwitch.Case<KeyNotFoundException>(() => { statusCode = HttpStatusCode.NotFound; }),
- TypeSwitch.Case<DivideByZeroException>(() => { statusCode = HttpStatusCode.MethodNotAllowed; }),
- TypeSwitch.Case<QueryFormatException>(() => { statusCode = HttpStatusCode.MethodNotAllowed; })
- );
- HttpResponse response = context.HttpContext.Response;
- response.StatusCode = (int)statusCode;
- response.ContentType = "application/json";
- var err = new ErrorPayload()
- {
- Data = data,
- StackTrace = ex.StackTrace,
- Message = ex.Message,
- StatusCode = (int)statusCode
- };
- response.WriteAsync(JsonConvert.SerializeObject(err));
- }
- }
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddApplicationInsightsTelemetry(Configuration);
- services.AddMvc( config =>
- {
- config.Filters.Add(typeof(GlobalExceptionFilter));
- }
- );
- }
- [HttpGet("{idCliente}")]
- public IActionResult GetCliente(int idCliente)
- {
- throw new QueryFormatException("My Custom Exception");
- }
Add Comment
Please, Sign In to add comment