我有以下情况:
- 我有几个实现基本异常的派生异常类
//Base exception type
public class SaberpsicologiaException : Exception
{
}
//One of the derived exception class
public class MovedPermanentlyException : SaberpsicologiaException
{
public string CannonicalUri { get; private set; }
public MovedPermanentlyException(string cannonicalUri)
: base($"Moved permanently to {cannonicalUri}")
{
this.CannonicalUri = cannonicalUri;
}
}
- 对于每个异常类,我想实现一个异常处理程序,它将返回一个 ActionResult,它将实现一个通用接口:
interface ISaberpsicologiaExceptionHandler<T>
where T : SaberpsicologiaException
{
ActionResult Result(T exception);
}
public class MovedPermanentlyExceptionHandler
: ISaberpsicologiaExceptionHandler<MovedPermanentlyException>
{
public ActionResult Result(MovedPermanentlyException exception)
{
var redirectResult = new RedirectResult(exception.CannonicalUri);
redirectResult.Permanent = true;
return redirectResult;
}
}
- 当我捕获从 SaberpsicologiaException 派生的异常时,我希望适当的处理程序运行:
public class ExceptionHandlerFilter : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
base.OnException(context);
HandleResponseCodeByExceptionType(context);
}
private void HandleResponseCodeByExceptionType(ExceptionContext context)
{
var exception = context.Exception;
if (!CanHandle(exception))
{
return;
}
var mapping = new Dictionary<Type, Type>
{
{ typeof(MovedPermanentlyException), typeof(MovedPermanentlyExceptionHandler) }
};
var handlerType = mapping[exception.GetType()];
var handler = Activator.CreateInstance(handlerType);
handler.Result(exception); //<- compilation error
//handler is type "object" and not MovedPermanentlyExceptionHandler
}
}
我尝试使用 Activator (Reflection) 来解决它,但我遇到了没有真正具有 ISaberpsicologiaExceptionHandler< [runtime exceptiontype] > 类型的对象的问题,因此我无法正确使用该类型。
总之,问题是我有一个异常类型,我想获得该异常类型的 ISaberpsicologiaExceptionHandler,我想我可以使用更多反射来执行“结果”方法,但我想多做一点优雅。