【问题标题】:C# ReactiveUI UserError wrong handlerC# ReactiveUI UserError 错误处理程序
【发布时间】:2016-08-31 08:57:36
【问题描述】:

我一直在使用 ReactiveUI 创建视图模型并将它们绑定到我的 WPF 视图。在这些视图模型中,我使用 UserError 来包装异常并将它们转发到关联的视图。

但是,我注意到当抛出 UserError 时,它并不总是在预期的处理程序中结束。为了解决这个问题,我使用 UserError.RegisterHandler<MyUserErrorSubclass>(myHandler) 将 UserError 子类化并仅为该子类注册了处理程序

这似乎有效,但并不能完全解决问题。 我现在有两个相同视图模型和关联视图的实例,但是在一个视图模型中引发的 UserError 最终出现在错误的视图中。这是一个问题,因为我想显示一条错误消息,但它显示在错误的视图中。

示例代码:

class ViewModel : ReactiveObject {
    ...
    public ReactiveCommand<object> ExampleCommand { get; }

    ViewModel(){
        ...

        ExampleCommand.ThrownExceptions.Subscribe(ex => UserError.Throw(new UserError("Error!")));
    }
}

class View : IViewFor<ViewModel> {
    ...
    Label exampleLabel;

    View(){
        ...
        UserError.RegisterHandler(userError => {
            exampleLabel.Text = userError.ErrorMessage;
        });
        ...
    }
    ...
}


ViewModel aModel = new ViewModel();
View aView = new View { ViewModel = aModel};

ViewModel bModel = new ViewModel();
View bView = new View { ViewModel = bModel};

调用aModel.Example() 设置bView.exampleLabel,而我需要设置aView.exampleLabel

解决此问题的最佳方法是什么?

【问题讨论】:

    标签: c# error-handling reactiveui


    【解决方案1】:

    我通过查看 ReactiveUI 源代码弄明白了。

    如果您在无法处理的处理程序中收到 UserError,则应该返回 null。然后将 UserError 传递给下一个注册的处理程序。

    示例代码:

    UserError.RegisterHandler(userError => {
        if(cannotHandleThisError){
            return null;
        }
        exampleLabel.Text = userError.ErrorMessage;
    });
    

    我继承了 UserError 并将抛出的视图模型存储在 usererror 中。我现在在执行前检查错误中的视图模型是否与处理程序视图模型匹配。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多