This repository has been archived on 2023-02-13. You can view files and clone it, but cannot push or open issues or pull requests.
gswi-server/gswi/Filters/CustomExceptionFilterAttribute.cs
2022-02-20 19:04:11 +01:00

55 lines
1.6 KiB
C#

using System;
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using NLog;
using gswi.Model.Filters;
namespace gswi.Filters
{
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
private static Logger _logger = LogManager.GetCurrentClassLogger();
public CustomExceptionFilterAttribute() { }
public override void OnException(ExceptionContext context)
{
context.Result = CreateJsonErrorResult(context);
base.OnException(context);
}
public JsonResult CreateJsonErrorResult(ExceptionContext context)
{
JsonResult result = null;
// create jsonresult
var exception = context.Exception;
if (exception is ServiceException)
{
var bex = exception as ServiceException;
_logger.Error($"{bex.GetDetailedMessage()}");
var error = new ErrorDto(bex.ErrorCode, bex.GetMessage());
result = new JsonResult(error)
{
StatusCode = (int)HttpStatusCode.BadRequest
};
}
else
{
var trackingId = Guid.NewGuid();
string userMsg = $"Tracking Id: {trackingId}";
_logger.Error(exception, userMsg);
var error = new ErrorDto($"Tracking Id: {trackingId}");
result = new JsonResult(error)
{
StatusCode = (int)HttpStatusCode.InternalServerError
};
}
return result;
}
}
}