ExceptionFilter相当于使用WebException详细信息的try catch

时间:2017-08-24 14:45:15

标签: c# asp.net asp.net-mvc asp.net-mvc-4

我目前有一个非常基本的全局错误过滤器:

public class HandleMyErrorAttribute : IExceptionFilter
{
    public void OnException(ExceptionContext context)
    {
        Exception raisedException = context.Exception;
        LogHelper.LogException(raisedException);
    }
}

这很好地处理了我的应用程序的错误。但是,在特定情况下,我想从异常中捕获更多细节。具体来说,如果异常是WebException(而不是通用Exception),我想要更多详细信息。为了解决这个问题,我在代码中的各个地方都有一些try-catch块。例如:

        //...
        //...Request object is created here
        try
        {
            WebResponse response = request.GetResponse();
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            JavaScriptSerializer jss = new JavaScriptSerializer();
            this.data = jss.Deserialize<RingCentralAuthenticatedModel>(responseFromServer);
            reader.Close();
            dataStream.Close();
            response.Close();
        }
        catch (WebException ex)
        {
            //I use this to capture more detailed info (headers, etc) if I get a WebException
            var msg = ex.Message + Environment.NewLine + Environment.NewLine + Environment.NewLine;
            msg += "Url: " + Environment.NewLine + Environment.NewLine + request.RequestUri + Environment.NewLine + Environment.NewLine;
            msg += "Request:" + Environment.NewLine + Environment.NewLine;
            foreach (var key in request.Headers.AllKeys)
                msg += key + " = " + request.Headers[key] + Environment.NewLine;
            msg += Environment.NewLine + Environment.NewLine;
            msg += "Response:" + Environment.NewLine + Environment.NewLine;
            foreach (var key in ex.Response.Headers.AllKeys)
                msg += key + " = " + ex.Response.Headers[key] + Environment.NewLine;
            //I then pass this more detailed info on to the generic error filter to be logged
            throw new Exception(msg);
        }

我想知道是否有更好的方法可以在HandleMyErrorAttribute单独(不使用try-catch块)中处理此问题。我的想法是检测我的过滤器中引发的异常是否为WebException,如果是,则提取日志的详细信息。与HandleMyErrorAttribute处理的try-catch块相同的是什么?

0 个答案:

没有答案