Guest User

Untitled

a guest
Sep 23rd, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. public class GlobalExceptionFilter : IExceptionFilter, IDisposable
  2. {
  3. private readonly ILogger _logger;
  4. public GlobalExceptionFilter(ILoggerFactory logger)
  5. {
  6. if (logger == null)
  7. {
  8. throw new ArgumentNullException(nameof(logger));
  9. }
  10.  
  11. this._logger = logger.CreateLogger("Global Exception Filter");
  12. }
  13.  
  14. public void Dispose()
  15. {
  16. }
  17.  
  18. public void OnException(ExceptionContext context)
  19. {
  20. Dictionary<string, string> data = new Dictionary<string, string>();
  21. HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
  22. String message = String.Empty;
  23.  
  24. var ex = context.Exception;
  25.  
  26. TypeSwitch.Do(ex,
  27. TypeSwitch.Case<ArgumentException>(() => { statusCode = HttpStatusCode.BadRequest; }),
  28. TypeSwitch.Case<ArgumentNullException>(() => { statusCode = HttpStatusCode.BadRequest; }),
  29. TypeSwitch.Case<ArgumentOutOfRangeException>(() => { statusCode = HttpStatusCode.BadRequest; }),
  30. TypeSwitch.Case<KeyNotFoundException>(() => { statusCode = HttpStatusCode.NotFound; }),
  31. TypeSwitch.Case<DivideByZeroException>(() => { statusCode = HttpStatusCode.MethodNotAllowed; }),
  32. TypeSwitch.Case<QueryFormatException>(() => { statusCode = HttpStatusCode.MethodNotAllowed; })
  33. );
  34.  
  35. HttpResponse response = context.HttpContext.Response;
  36. response.StatusCode = (int)statusCode;
  37. response.ContentType = "application/json";
  38. var err = new ErrorPayload()
  39. {
  40. Data = data,
  41. StackTrace = ex.StackTrace,
  42. Message = ex.Message,
  43. StatusCode = (int)statusCode
  44. };
  45. response.WriteAsync(JsonConvert.SerializeObject(err));
  46. }
  47. }
  48.  
  49. public void ConfigureServices(IServiceCollection services)
  50. {
  51. services.AddApplicationInsightsTelemetry(Configuration);
  52. services.AddMvc( config =>
  53. {
  54. config.Filters.Add(typeof(GlobalExceptionFilter));
  55. }
  56. );
  57. }
  58.  
  59. [HttpGet("{idCliente}")]
  60. public IActionResult GetCliente(int idCliente)
  61. {
  62. throw new QueryFormatException("My Custom Exception");
  63. }
Add Comment
Please, Sign In to add comment