首页 > 解决方案 > 如何获取有关 AnimationException 的更多信息?

问题描述

我有一个 WPF 应用程序,我在其中创建了一个Storyboard动画控件。触发动画后,项目中断,但我从 Visual Studio 得到的只是以下输出消息:

Exception thrown: 'System.Windows.Media.Animation.AnimationException' in WindowsBase.dll

如何获得更多信息,以便我确切知道问题出在哪里?该文档仅指出

为属性设置动画时发生错误时引发的异常。

我不知道代码在哪一行中断以插入一个try-catch块。

标签: c#wpfanimationexceptiontry-catch

解决方案


首先,我会像这样捕获这些未处理的异常:

public MyCustomControl()
{
  Dispatcher.UnhandledException += Dispatcher_UnhandledException;
}

void Dispatcher_UnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
  switch (e.Exception)
  {
    case AnimationException aniEx:
      Log(aniEx.GetDetails());
      break;
    // ...
    // default: ...
  }
}

其次,我会为异常添加一个 GetDetails 扩展,以从中获取所有详细信息:

public static class Extensions
{
    /// <summary>
    /// Returns all Details of an exception
    /// </summary>
    /// <param name="exception"></param>
    /// <returns></returns>
    public static string GetDetails(this Exception exception)
    {
        string GetInnerExceptionDetails(Exception e)
        {
            var s = new StringBuilder(e.GetType().FullName);
            if (e.GetType().GetProperties()
                 .Select(prop => new { prop.Name, Value = prop.GetValue(e, null) })
                 .Select(x => $"{x.Name}: {x.Value ?? string.Empty}").ToList() is List<string> props && props.Any())
            {
                s.AppendLine(string.Join(Environment.NewLine, props));
                s.AppendLine();
            }

            if (e.InnerException != null)
                s.AppendLine(GetInnerExceptionDetails(e.InnerException));
            return s.ToString();
        }
        return GetInnerExceptionDetails(exception);
    }
}

推荐阅读