.NET-在泛型方法上删除了异常堆栈跟踪行



(最初的内容被编辑掉了,因为我发现它无关紧要)

我的应用程序有一个通用的RESTful HTTP客户端,它将操作封装在委托,并且已通过我的WrapOperation方法(如下所示)。

但是,当引发异常时,堆栈跟踪只包含一个条目:

at MyProject.Client.RestClient.WrapOperation[T](String method, String path, Object requestObject, RestOperation`1 action) in D:{fileName}RestClient.cs:line 196

我已经将问题代码简化为:

private T WrapOperation<T>(String method, String path, Object requestObject, RestOperation<T> action) {
        HttpWebRequest request;
        RestTransaction txn = CreateRequest(method, path, requestObject, out request);
        ////////////////////////////
        try {
            throw new WebException("testing stack trace 6");
            throw new Exception("testing stack trace 7");
            using(HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
                txn.GotResponse( response );
                return action( txn, response );
            }
        } catch(WebException wex) {
            // NOTE: When exceptions are caught, they're missing the first few entries of the stack trace
            // And appear as though "WrapOperation[T]" (sic) is the entrypoint. Why is this?

            if( wex.Response != null ) {
                HttpWebResponse response = (HttpWebResponse)wex.Response;
                txn.GotResponse( wex, response );
                CopyResponseToMemoryStream( response, txn ).Dispose();
            } else {
                txn.GotResponse( wex );
            }
            // NOTE: However, when these RestExceptions are caught (by WrapOperation's caller), their stack trace is complete and shows the entire trace
            throw new RestException("WebExeption during GetResponse.", txn, wex );
        } catch(Exception ex) {
            txn.GotResponse( ex );
            // NOTE: However, when these RestExceptions are caught (by WrapOperation's caller), their stack trace is complete and shows the entire trace
            throw new RestException("Non-WebException during GetResponse.", txn, ex );
        }
    }

当抛出"测试堆栈跟踪6"异常时,当被catch(WebException wex)捕获时,wex的堆栈跟踪只包含一个条目。

为什么会这样?

看起来像是将原始异常包装到自定义异常类中。当您读取异常以查看堆栈跟踪时,您还必须检查内部异常行以获取完整的跟踪。

编辑-

堆栈跟踪从抛出异常的地方开始,所以显示的堆栈跟踪是正确的,我对问题的原始描述也是正确的。

任何时候抛出一个新的异常,该异常的堆栈跟踪都会从该点开始。

在您的原始示例中,再次检查此处的内部异常:

//throwing the exception resets the stack trace!
//the next catch will see the exception as coming from this line, and
//will need to look at the inner exception at that point to see the
//original exception! I Think! I have no idea what RestException is,
//only that your passing the original exception ex into it as a parameter.
throw new RestException("Non-WebException during GetResponse.", txn, ex );

如果您的一个(未显示)方法正在捕获异常,然后像这样重新抛出:

throw ex;

然后,堆栈跟踪将重置为从重新抛出点开始。

throw;

将维护堆栈跟踪。

最新更新