我正在使用.NET Core 3.1。我使用ExceptionFilterAttribute处理整个应用程序中的错误。我还具有一个称为WarningException的自定义异常类。问题是WarningException类型在ExceptionFilterAttribute中未被识别为WarningException,但被识别为System.Exception。怎么可能呢?
public class CustomErrorAttribute : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
base.OnException(context);
if (context.ExceptionHandled)
return;
context.ExceptionHandled = true;
int statusCode = 500;
string status = "Internal Server Error";
string header = "Internal Server Error";
if (context.Exception is WarningException) //exception does not pass this `if`
{
var ex = context.Exception as WarningException;
statusCode = (int)ex.StatusCode;
status = ex.Status;
header = "Warning";
}
}
}
public class WarningException : Exception
{
public WarningException(string message)
: base(message)
{
}
public HttpStatusCode StatusCode => HttpStatusCode.NoContent;
public string Status => "No Content";
}
public ActionResult Index()
{
throw new WarningException("This custom error should be catched as WarningException NOT System.Exception");
}