Обработка исключений, возникающих при создании ReactiveCommand способом ReactiveUI - PullRequest
0 голосов
/ 29 декабря 2018

Я только начал изучать 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; }
    }
}
...