0
以下は私の実装です。私はを書きました。ExceptionFilterAttributeから継承したCustomExceptionFilterAttributeがあります。各エラーはifとelseの中に置かれ、適切な結果が生成されます。私がしたいのは、コールバック関数を作成して、ifとelseを取り除くことができ、ブロックとエラーをより一般的な方法で処理できるようにすることです。asp.netコア2.0で汎用ExceptionFitlerを書く
public class HostedServicesController : BaseController
{
public IActioResult Index()
{
throw new NotFoundInDatabaseException("Error in Index Controller");
}
}
public class NotFoundInDatabaseException : Exception
{
public NotFoundInDatabaseException(string objectName, object objectId) :
base(message: $"No {objectName} with id '{objectId}' was found")
{
}
}
public class CustomExceptionFilterAttribute :ExceptionFilterAttribute
{
private SystemManager SysMgr { get; }
public CustomExceptionFilterAttribute(SystemManager systemManager)
{
SysMgr = systemManager;
}
public override void OnException(ExceptionContext context)
{
var le = SysMgr.Logger.NewEntry();
try
{
le.Message = context.Exception.Message;
le.AddException(context.Exception);
var exception = context.Exception;
if (exception is NotFoundInDatabaseException)
{
le.Type = LogType.ClientFaultMinor;
context.Result = new NotFoundObjectResult(new Error(ExceptionCode.ResourceNotFound, exception.Message));
}
else if (exception is ConfigurationException)
{
le.Type = LogType.ErrorMinor;
context.Result = new BadRequestObjectResult(new Error(ExceptionCode.NotAuthorised, exception.Message));
}
else
{
le.Type = LogType.ErrorSevere;
context.Result = new InternalServerErrorObjectResult(new Error(ExceptionCode.Unknown, exception.Message));
}
le.AddProperty("context.Result", context.Result);
//base.OnException(context);
}
finally
{
Task.Run(() => SysMgr.Logger.LogAsync(le)).Wait();
}
}
}