public class CommonExceptionsFilter : ExceptionFilterAttribute
{
private readonly ILogger logger;
public CommonExceptionsFilter(ILogger<CommonExceptionsFilter> logger)
{
this.logger = logger;
}
public override void OnException(ExceptionContext context)
{
context.HttpContext.Response.GetTypedHeaders().ContentType = null;
bool isWarning = false;
if (context.Exception is NotFoundException notFoundException)
{
isWarning = true;
if(!string.IsNullOrWhiteSpace(notFoundException.Message))
{
Dictionary<string, string[]> output = new Dictionary<string, string[]>();
output.Add("Message", new string[] { notFoundException.Message });
context.Result = new ObjectResult(output);
}
context.HttpContext.Response.StatusCode = StatusCodes.Status404NotFound;
}
else if (context.Exception is ArgumentException argumentException)
{
isWarning = true;
Dictionary<string, string[]> output = new Dictionary<string, string[]>();
// remove the last line from the message as it repeats the parameter name
string paramName = string.IsNullOrWhiteSpace(argumentException.ParamName) ? null : argumentException.ParamName;
string message = argumentException.Message.Contains(Environment.NewLine)
? argumentException.Message.Substring(0, argumentException.Message.LastIndexOf(Environment.NewLine))
: argumentException.Message;
output.Add(paramName ?? "Argument", new string[] { message });
context.Result = new BadRequestObjectResult(output);
context.HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
}
else
{
context.Result = new ObjectResult(new { Error = new string[] { context.Exception.Message } });
context.HttpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
}
context.ExceptionHandled = true;
if (isWarning)
{
logger.LogWarning(new EventId(context.HttpContext.Response.StatusCode), context.Exception, context.Exception.Message);
}
else
{
logger.LogError(new EventId(context.HttpContext.Response.StatusCode), context.Exception, context.Exception.Message);
}
base.OnException(context);
}
}
No comments:
Post a Comment