【问题标题】:Handling Exceptions in MVC4 when API Controller creation fails?API 控制器创建失败时处理 MVC4 中的异常?
【发布时间】:2013-07-26 17:16:12
【问题描述】:

我在创建 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);
}

没有任何区别。

如何处理在调用控制器之前发生的错误?

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-4 error-handling asp.net-web-api


    【解决方案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;
            }
        }
        ...
    

    【讨论】:

    • 如果是这样的话,这是有道理的。我必须尽快阅读 mvc 源代码。
    猜你喜欢
    • 1970-01-01
    • 2018-12-06
    • 1970-01-01
    • 1970-01-01
    • 2013-01-10
    • 1970-01-01
    • 2022-11-29
    • 2018-03-30
    • 1970-01-01
    相关资源
    最近更新 更多