asp.Net   发布时间:2022-04-04  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了ASP.NET C#捕获类中的所有异常大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我知道这不是办法,而且根本不干净。我只是想知道是否可能。

如果我有一个类有一堆方法@H_772_3@

public class Foo {

   methodA() {}

   methodB() {}

   methodC() {}

}

是否可能捕获可能发生的所有异常,而不必在每个方法中写入try / catch?@H_772_3@

解决方法

是的。最简单的方法就是这样一个属性:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,AllowMultiple = false,Inherited = truE)]
public class HandleErrorAttribute : FilterAttribute,IExceptionFilter
{

    public void OnException(ExceptionContext filterContext)
    {
        if (filterContext == null)
        {
            throw new ArgumentNullException("filterContext");
        }

        if (filterContext.ExceptionHandled)
        {
            return;
        }

        var exception = filterContext.Exception;

        // that need to be your current request object. In this case I use a custom one so I must fetch it from the items collection of the current request,where I had stored it before.
        var request = filterContext.httpContext.Items[request.requestKey] as request;

        if (request != null)
        {
            // overwrite ErrorResponse with a response object of your choice or write directly to the filterContext.httpContext.Response
            var errorResponse = new ErrorResponse(request,exception); 
            errorResponse.Write(filterContext.httpContext.ResponsE);
            filterContext.ExceptionHandled = true;
        }
    }
}

// Or a just slightly modified version of the default ASP.Net MVC HandleError Attribute
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class,Inherited = true,AllowMultiple = truE)]
    public class CustomHandleErrorAttribute : FilterAttribute,IExceptionFilter
    {
        // Fields
        private const String _defaultView = "Error";
        private String _master;
        private readonly object _typEID = new object();
        private String _view;

        // Methods
        public virtual void OnException(ExceptionContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            if (!filterContext.IsChildAction && (!filterContext.ExceptionHandled && filterContext.httpContext.IsCustomErrorEnabled))
            {
                Exception innerException = filterContext.Exception;
                if ((new httpException(null,innerException).GethttpCode() == 500))
                {
                    String controllerName = (String)filterContext.RouteData.Values["controller"];
                    String actionName = (String)filterContext.RouteData.Values["action"];
                    HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception,controllerName,actionName);
                    ViewResult result = new ViewResult();
                    result.ViewName = this.View;
                    result.MasterName = this.Master;
                    result.ViewData = new ViewDataDictionary<HandleErrorInfo>(model);
                    result.TemPDAta = filterContext.Controller.TemPDAta;
                    filterContext.Result = result;
                    filterContext.ExceptionHandled = true;
                    filterContext.httpContext.Response.Clear();
                    filterContext.httpContext.Response.StatusCode = 500;
                    filterContext.httpContext.Response.TrySkipIisCustomErrors = true;
                }
            }
        }

        public String Master
        {
            get
            {
                return (this._master ?? String.Empty);
            }
            set
            {
                this._master = value;
            }
        }

        public override object TypEID
        {
            get
            {
                return this._typEID;
            }
        }

        public String View
        {
            get
            {
                if (String.IsNullOrEmpty(this._view))
                {
                    return "Error";
                }
                return this._view;
            }
            set
            {
                this._view = value;
            }
        }
    }

用法(未经测试的原因我在已经实现所有必需接口的控制器的上下文中使用它)@H_772_3@

[HandleErrorAttribute]
public class Foo : IExceptionFilter // (I am not sure about this one IActionFilter)
{

    public void MethodA() 
    {
        // body
    }

    public void MethodB() 
    {
        // body
    }

    public void MethodC()
    {
        // body
    }

}

或者你可以这样做:@H_772_3@

public class ExecuteHelper
{
    public static void Catch(Action action)
    {
        try
        {
            action();
        }
        catch (Exception eX)
        {
            // Do what you want
        }
    }
}

并在功能体中使用它:@H_772_3@

public void Foo(String something)
{
    ExecuteHelper.Catch(() =>
    {
        // Do something with something or without something
    });
}

大佬总结

以上是大佬教程为你收集整理的ASP.NET C#捕获类中的所有异常全部内容,希望文章能够帮你解决ASP.NET C#捕获类中的所有异常所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。