以ReactiveUI方式处理在创建ReactiveCommand时引发的异常

时间:2018-12-29 11:55:18

标签: c# wpf exception-handling reactiveui

我刚刚开始学习ReactiveUI,已经阅读并启动了ReactiveDemo(https://reactiveui.net/docs/getting-started/ https://github.com/reactiveui/ReactiveUI/tree/master/samples/getting-started)。

我注意到,当缺少找到的项目的URL时,NugetDetailsViewModel.ProjectUrl变量将得到null,而当用户尝试打开项目站点时,将引发NullReferenceException。

我尝试使用OpenPage.ThrownExceptions.Subscribe()处理此错误,但是没有用。

所以我的问题是,如何使用ReactiveUI方式?我知道我可以在try-catch周围写Process.Start()块,但这并不酷,对吧? :)

我的NugetDetailsViewModel.cs代码(稍作编辑):

using System;
using System.Windows;
using System.Diagnostics;
using System.Reactive;
using NuGet.Protocol.Core.Types;
using ReactiveUI;

namespace ReactiveDemo
{
    // This class wraps out NuGet model object into a ViewModel and allows
    // us to have a ReactiveCommand to open the NuGet package URL.
    public class NugetDetailsViewModel : ReactiveObject
    {
        private readonly IPackageSearchMetadata _metadata;
        private readonly Uri _defaultUrl;

        public NugetDetailsViewModel(IPackageSearchMetadata metadata)
        {
            _metadata = metadata;
            _defaultUrl = new Uri("https://git.io/fAlfh");

            OpenPage = ReactiveCommand.Create(() =>
            {
                Process.Start(ProjectUrl.ToString()); // exception is thrown here when ProjectUrl is null
            });

            OpenPage.ThrownExceptions.Subscribe(error =>
            {
                MessageBox.Show(error.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }); // doesn't work
        }

        public Uri IconUrl => _metadata.IconUrl ?? _defaultUrl;
        public string Description => _metadata.Description;
        public Uri ProjectUrl => _metadata.ProjectUrl;
        public string Title => _metadata.Title;

        // ReactiveCommand allows us to execute logic without exposing any of the 
        // implementation details with the View. The generic parameters are the 
        // input into the command and it's output. In our case we don't have any 
        // input or output so we use Unit which in Reactive speak means a void type.
        public ReactiveCommand<Unit, Unit> OpenPage { get; }
    }
}

0 个答案:

没有答案