SHARE
TWEET

Untitled

a guest Jan 24th, 2020 74 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.   public class ExceptionHandlerFilterAttribute :  ExceptionFilterAttribute
  2.     {
  3.         private readonly ILogger _logger;
  4.         public ExceptionHandlerFilterAttribute(ILogger<ExceptionHandlerFilterAttribute> logger)
  5.         {
  6.             _logger = logger;
  7.         }
  8.  
  9.         public override void OnException(ExceptionContext context)
  10.         {
  11.             _logger.LogError(context.Exception, $"Error during {context.HttpContext.Request.Path}");
  12.             if (!(context.Exception is IHasUserMessageException))
  13.             {
  14.                 context.Result = new StatusCodeResult(StatusCodes.Status500InternalServerError);
  15.                 return;
  16.             }
  17.  
  18.             switch (context.Exception)
  19.             {
  20.                 case ValidationException e:
  21.                     context.Result = new BadRequestObjectResult(new { Success = false, ErrorMessage = e.Message});                    
  22.                     break;
  23.                 case HashCollisionException e:
  24.                     context.Result = new ConflictObjectResult(new { Success = false, ErrorMessage = e.Message });
  25.                     break;
  26.                 case InvalidMessageFormatException e:
  27.                     context.Result = new BadRequestObjectResult(new { Success = false, ErrorMessage = e.Message });
  28.                     break;
  29.                 case EventTimedOutValidationException e:
  30.                     context.Result = new BadRequestObjectResult(new { Success = false, ErrorMessage = e.Message });
  31.                     break;
  32.                 case InconsistentInputDataException e:
  33.                     context.Result = new BadRequestObjectResult(new { Success = false, ErrorMessage = e.Message });
  34.                     break;
  35.                 case UnauthorizedException e:
  36.                     context.Result = new ObjectResult(new { Success = false, ErrorMessage = e.Message }) { StatusCode = StatusCodes.Status401Unauthorized };
  37.                     break;
  38.                 default:
  39.                     context.Result = new BadRequestObjectResult(new { Success = false, ErrorMessage = context.Exception });
  40.                     break;                  
  41.             }
  42.         }
  43.     }
  44.  
  45.  
  46.   [Route("api/[controller]")]
  47.     [ServiceFilter(typeof(ExceptionHandlerFilterAttribute))]
  48.  
  49.     public class EventsController : ControllerBase
  50.     {......}
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top