-2

如何轻松获取所有异常消息,包括 C# 中的 InnerExceptions,以输出到控制台或日志记录?

4

2 回答 2

2

通常你只需循环:

catch (Exception ex)
{
    while (ex != null)
    {
        Console.Error.WriteLine(ex.Message);
        ex = ex.InnerException;
    }
}
于 2018-07-25T12:50:28.180 回答
2

最简单的方法是编写一个递归函数:

例如:

    public static string ExceptionMessages(Exception ex)
    {
        if (ex.InnerException == null)
        {
            return ex.Message;
        }

        return ex.Message + "  " + ExceptionMessages(ex.InnerException);

    }

这将在单个字符串中输出所有消息。

于 2018-07-25T12:48:37.740 回答