我在创建api控制器时遇到错误,因为我没有为webapi设置autofac 。
但是,我似乎无法在任何地方发现异常。
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Type 'MyWeb.Web.Controllers.MyController' does not have a default constructor
</ExceptionMessage>
<ExceptionType>System.ArgumentException</ExceptionType>
<StackTrace>
at System.Linq.Expressions.Expression.New(Type type) at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
</StackTrace>
</Error>
我尝试为Elmah添加WebApi contrib,然后我添加了这个:
config.Filters.Add(new Elmah.Contrib.WebApi.ElmahHandleErrorApiAttribute());
没有让elmah注册例外。 我将以下内容添加到global.asax:
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
}
完全没有任何区别。
如何在调用控制器之前处理发生的错误?
答案 0 :(得分:1)
我想知道这个异常是否只是被添加到HttpResponseMessage的内容中,但实际上并没有被抛出作为异常。在构造函数实例化期间实现依赖项解析程序类时,尝试解析,捕获异常并返回null
通常是有意义的。
例如,在非API MVC控制器中,我经常使用this之类的东西:
public class UnityDependencyResolver : IDependencyResolver
{
public readonly IUnityContainer Container;
public UnityDependencyResolver(IUnityContainer container)
{
Container = container;
}
#region IDependencyResolver Members
public object GetService(Type serviceType)
{
try
{
return Container.Resolve(serviceType);
}
catch (Exception ex)
{
if (ex.InnerException is TypeInitializationException)
throw ex.InnerException;
return null;
}
}
...