如何隐藏异常堆栈跟踪在.NET当前的方法? [英] How to hide the current method from exception stack trace in .NET?

查看:302
本文介绍了如何隐藏异常堆栈跟踪在.NET当前的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种方法可以从方法内抛出一个异常,但不包括在异常堆栈跟踪的方法。例如,

I'd like to know if there is a way to throw an exception from inside a method, but to not include that method in the exception stack trace. E.g.

void ThrowSomeException()
{
    throw new SomeException();
}

然后,如果我调用该方法从一个叫方法美孚()我要的异常堆栈跟踪下手在富() ,不是在ThrowSomeException()。我想如果这是可能的它可能是通过该方法的使用属性。

And then, if I call that method from a method called Foo() I want the exception stack trace to start with at Foo(), not at ThrowSomeException(). I assume if this was possible it might be through the use of attributes on the method.

我感兴趣的是一般的答案,但如果这是不可能的,我真正想要做的就是创建一个扩展方法 assertEqual便()的IEnumerable ,我会在NUnit的测试中使用。所以,当我打电话 myEnumerable.AssertEqual(otherEnumerable)和失败,NUnit的应当报告该错误的测试方法中,没有内部的扩展方法。

I'm interested in the general answer, but in case this isn't possible, what I'm really trying to do is create an extension method AssertEqual() for IEnumerable that I'll use in NUnit tests. So when I call myEnumerable.AssertEqual(otherEnumerable) and it fails, NUnit should report the error inside the test method, not inside the extension method.

谢谢!

推荐答案

也许你可以得到自己的异常类型和覆盖堆栈跟踪属性的getter来排除方法:

Maybe you could derive your own exception type and override the StackTrace property getter to exclude your method:

using System;
using System.Collections.Generic;

class MyException : Exception {

    string _excludeFromStackTrace;

    public MyException(string excludeFromStackTrace) {
        _excludeFromStackTrace = excludeFromStackTrace;
    }

    public override string StackTrace {
        get {
            List<string> stackTrace = new List<string>();
            stackTrace.AddRange(base.StackTrace.Split(new string[] {Environment.NewLine},StringSplitOptions.None));
            stackTrace.RemoveAll(x => x.Contains(_excludeFromStackTrace));
            return string.Join(Environment.NewLine, stackTrace.ToArray());
        }
    }
}

class Program {

    static void TestExc() {
        throw new MyException("Program.TestExc");
    }

    static void foo() {
        TestExc();
    }

    static void Main(params string[] args) {
        try{
            foo();
        } catch (Exception exc){
            Console.WriteLine(exc.StackTrace);
        }
    }

}

这篇关于如何隐藏异常堆栈跟踪在.NET当前的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆