AttributeUsage AttributeTargets Class AttributeTargets Method public c

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
private static readonly Dictionary<Type, HttpStatusCode> errors = new Dictionary<Type, HttpStatusCode>()
{
[typeof(NotFoundException)] = HttpStatusCode.NotFound,
[typeof(AccessDeniedException)] = HttpStatusCode.Forbidden,
[typeof(AccessDeniedException)] = HttpStatusCode.BadRequest,
};
public override void OnException(ExceptionContext context)
{
context.HttpContext.Response.ContentType = "application/json";
var exception = context.Exception.GetType();
if(errors.TryGetValue(exception, out var status))
{
context.HttpContext.Response.StatusCode = (int) status;
context.Result = new JsonResult(new
{
errors = new[] { context.Exception.Message }
});
return;
}
context.HttpContext.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
context.Result = new JsonResult(new
{
errors = new[] { context.Exception.Message },
stackTrace = context.Exception.StackTrace
});
}
}