forked from reactiveui/ReactiveUI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathErrors.cs
More file actions
412 lines (365 loc) · 17.1 KB
/
Errors.cs
File metadata and controls
412 lines (365 loc) · 17.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
using System;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.Reactive.Subjects;
using System.Reactive.Threading.Tasks;
using System.Threading.Tasks;
namespace ReactiveUI
{
/// <summary>
/// Describes a stock error icon situation - it is up to the UI to decide
/// how to interpret these icons.
/// </summary>
public enum StockUserErrorIcon {
Critical,
Error,
Question,
Warning,
Notice,
};
/// <summary>
/// A command that represents a recovery from an error. These commands
/// will typically be displayed as buttons in the error dialog.
/// </summary>
public interface IRecoveryCommand : IReactiveCommand
{
/// <summary>
/// The command name, typically displayed as the button text.
/// </summary>
string CommandName { get; }
/// <summary>
/// When the command is invoked and a result is determined, the
/// command should set the recovery result to indicate the action the
/// throwing code should take.
/// </summary>
RecoveryOptionResult? RecoveryResult { get; }
}
/// <summary>
/// RecoveryOptionResult describes to the code throwing the UserError what
/// to do once the error is resolved.
/// </summary>
public enum RecoveryOptionResult {
/// <summary>
/// The operation should be cancelled, but it is no longer an error.
/// </summary>
CancelOperation,
/// <summary>
/// The operation should be retried with the same parameters.
/// </summary>
RetryOperation,
/// <summary>
/// Recovery failed or not possible, you should rethrow as an
/// Exception.
/// </summary>
FailOperation,
};
/// <summary>
/// User Errors are similar to Exceptions, except that they are intended
/// to be displayed to the user. As such, your error messages should be
/// phrased in a friendly way. When a UserError is thrown, code higher up
/// in the stack has a chance to resolve the UserError via a user
/// interaction.
///
/// Code can also add "Recovery Options" which resolve user errors: for
/// example an "Out of Disk Space" error might have an "Open Explorer"
/// recovery option.
/// </summary>
public class UserError : ReactiveObject
{
public UserError(
string errorMessage,
string errorCauseOrResolution = null,
IEnumerable<IRecoveryCommand> recoveryOptions = null,
Dictionary<string, object> contextInfo = null,
Exception innerException = null)
{
RecoveryOptions = new ReactiveList<IRecoveryCommand>(recoveryOptions ?? Enumerable.Empty<IRecoveryCommand>());
ErrorCauseOrResolution = errorCauseOrResolution;
ContextInfo = contextInfo ?? new Dictionary<string, object>();
UserErrorIcon = StockUserErrorIcon.Warning;
InnerException = innerException;
ErrorMessage = errorMessage;
}
/// <summary>
/// A Dictionary that allows UserErrors to contain arbitrary
/// application data.
/// </summary>
public Dictionary<string, object> ContextInfo { get; protected set; }
ReactiveList<IRecoveryCommand> _RecoveryOptions;
/// <summary>
/// The list of available Recovery Options that will be presented to
/// the user to resolve the issue - these usually correspond to
/// buttons in the dialog.
/// </summary>
public ReactiveList<IRecoveryCommand> RecoveryOptions {
get { return _RecoveryOptions; }
protected set { this.RaiseAndSetIfChanged(ref _RecoveryOptions, value); }
}
/// <summary>
/// The "Newspaper Headline" of the message being conveyed to the
/// user. This should be one line, short, and informative.
/// </summary>
public string ErrorMessage { get; set; }
/// <summary>
/// Additional optional information to describe what is happening, or
/// the resolution to an information-only error (i.e. a dialog to tell
/// the user that something has happened)
/// </summary>
public string ErrorCauseOrResolution { get; set; }
/// <summary>
/// This object is either a custom icon (usually an ImageSource), or
/// it can also be a StockUserErrorIcon. It can also be an
/// application-defined type that the handlers know to interpret.
/// </summary>
public object UserErrorIcon { get; set; }
/// <summary>
/// Optionally, The actual Exception that warranted throwing the
/// UserError.
/// </summary>
public Exception InnerException { get; protected set; }
//
// Static API
//
[ThreadStatic] static Func<UserError, IObservable<RecoveryOptionResult>> overriddenRegisteredUserErrorHandlers;
static readonly List<Func<UserError, IObservable<RecoveryOptionResult>>> registeredUserErrorHandlers = new List<Func<UserError, IObservable<RecoveryOptionResult>>>();
/// <summary>
/// Initiate a user interaction (i.e. "Throw the error to the user to
/// deal with") - this method is the simplest way to prompt the user
/// that an error has occurred.
/// </summary>
/// <param name="errorMessage">The message to show to the user. The
/// upper level handlers registered with RegisterHandler are
/// ultimately responsible for displaying this information.</param>
/// <param name="innerException">The Exception that was thrown, if
/// relevant - this will *not* ever be shown to the user.</param>
/// <returns>An Observable representing the action the code should
/// attempt to take, if any.</returns>
public static IObservable<RecoveryOptionResult> Throw(string errorMessage, Exception innerException = null)
{
return Throw(new UserError(errorMessage, innerException: innerException));
}
/// <summary>
/// Initiate a user interaction (i.e. "Throw the error to the user to
/// deal with").
/// </summary>
/// <param name="error">The UserError to show to the user. The
/// upper level handlers registered with RegisterHandler are
/// ultimately responsible for displaying this information. </param>
/// <returns></returns>
public static IObservable<RecoveryOptionResult> Throw(UserError error)
{
var handlers = (overriddenRegisteredUserErrorHandlers != null) ?
new[] { overriddenRegisteredUserErrorHandlers } :
registeredUserErrorHandlers.ToArray().Reverse();
// NB: This is a little complicated - here's the idea: we have a
// list of handlers that we're running down *in order*. If we find
// one that doesn't return null, we're going to return this as an
// Observable with one item (the result).
//
// If *none* of the handlers are interested in this UserError, we're
// going to OnError the Observable.
var handler = handlers.Select(x => x(error)).FirstOrDefault(x => x != null) ?? Observable.Empty<RecoveryOptionResult>()
.Concat(Observable.Throw<RecoveryOptionResult>(new UnhandledUserErrorException(error)));
var ret = handler.Take(1).PublishLast();
ret.Connect();
return ret;
}
/// <summary>
/// Register code to handle a UserError. Registered handlers are
/// called in reverse order to their registration (i.e. the newest
/// handler is called first), and they each have a chance to handle a
/// UserError.
///
/// If a Handler cannot resolve a UserError, it should return null
/// instead of an Observable result.
/// </summary>
/// <param name="errorHandler">A method that can handle a UserError,
/// usually by presenting it to the user. If the handler cannot handle
/// the error, it should return null.</param>
/// <returns>An IDisposable which will unregister the handler.</returns>
public static IDisposable RegisterHandler(Func<UserError, IObservable<RecoveryOptionResult>> errorHandler)
{
registeredUserErrorHandlers.Add(errorHandler);
return Disposable.Create(() => registeredUserErrorHandlers.Remove(errorHandler));
}
/// <summary>
/// Register code to handle a specific type of UserError. Registered
/// handlers are called in reverse order to their registration (i.e.
/// the newest handler is called first), and they each have a chance
/// to handle a UserError.
///
/// If a Handler cannot resolve a UserError, it should return null
/// instead of an Observable result.
/// </summary>
/// <param name="errorHandler">A method that can handle a UserError,
/// usually by presenting it to the user. If the handler cannot handle
/// the error, it should return null.</param>
/// <returns>An IDisposable which will unregister the handler.</returns>
public static IDisposable RegisterHandler<TException>(Func<TException, IObservable<RecoveryOptionResult>> errorHandler)
where TException : UserError
{
return RegisterHandler(x => {
if (!(x is TException)) {
return null;
}
return errorHandler((TException) x);
});
}
/// <summary>
/// Register code to handle a UserError. Registered handlers are
/// called in reverse order to their registration (i.e. the newest
/// handler is called first), and they each have a chance to handle a
/// UserError.
///
/// If a Handler cannot resolve a UserError, it should return null
/// instead of an Observable result.
/// </summary>
/// <param name="errorHandler">A method that can handle a UserError,
/// usually by presenting it to the user. If the handler cannot handle
/// the error, it should return null.</param>
/// <returns>An IDisposable which will unregister the handler.</returns>
public static IDisposable RegisterHandler(Func<UserError, Task<RecoveryOptionResult>> errorHandler)
{
return RegisterHandler(x => errorHandler(x).ToObservable());
}
/// <summary>
/// Register code to handle a specific type of UserError. Registered
/// handlers are called in reverse order to their registration (i.e.
/// the newest handler is called first), and they each have a chance
/// to handle a UserError.
///
/// If a Handler cannot resolve a UserError, it should return null
/// instead of an Observable result.
/// </summary>
/// <param name="errorHandler">A method that can handle a UserError,
/// usually by presenting it to the user. If the handler cannot handle
/// the error, it should return null.</param>
/// <returns>An IDisposable which will unregister the handler.</returns>
public static IDisposable RegisterHandler<TException>(Func<TException, Task<RecoveryOptionResult>> errorHandler)
where TException : UserError
{
return RegisterHandler(x => {
if (!(x is TException)) {
return null;
}
return errorHandler((TException)x).ToObservable();
});
}
/// <summary>
/// This method is a convenience wrapper around RegisterHandler that
/// adds the specified RecoveryCommand to any UserErrors that match
/// its filter.
/// </summary>
/// <param name="command">The RecoveryCommand to add.</param>
/// <param name="filter">An optional filter to determine which
/// UserErrors to add the command to.</param>
/// <returns>An IDisposable which will unregister the handler.</returns>
public static IDisposable AddRecoveryOption(IRecoveryCommand command, Func<UserError, bool> filter = null)
{
return RegisterHandler(x => {
if (filter != null && !filter(x)) {
return null;
}
if (!x.RecoveryOptions.Contains(command)) {
x.RecoveryOptions.Add(command);
}
return Observable.Empty<RecoveryOptionResult>();
});
}
/// <summary>
/// This method replaces *all* UserError handlers with the specified
/// handler. Use it for testing code that may throw UserErrors.
/// </summary>
/// <param name="errorHandler">The replacement UserError handler.</param>
/// <returns>An IDisposable which will unregister the test handler.</returns>
public static IDisposable OverrideHandlersForTesting(Func<UserError, IObservable<RecoveryOptionResult>> errorHandler)
{
overriddenRegisteredUserErrorHandlers = errorHandler;
return Disposable.Create(() => overriddenRegisteredUserErrorHandlers = null);
}
/// <summary>
/// This method replaces *all* UserError handlers with the specified
/// handler. Use it for testing code that may throw UserErrors.
/// </summary>
/// <param name="errorHandler">The replacement UserError handler.</param>
/// <returns>An IDisposable which will unregister the test handler.</returns>
public static IDisposable OverrideHandlersForTesting(Func<UserError, RecoveryOptionResult> errorHandler)
{
return OverrideHandlersForTesting(x => Observable.Return(errorHandler(x)));
}
}
/// <summary>
/// This Exception will be thrown when a UserError is not handled by any
/// of the registered handlers.
/// </summary>
public class UnhandledUserErrorException : Exception
{
public UnhandledUserErrorException(UserError error) : base(error.ErrorMessage, error.InnerException)
{
ReportedError = error;
}
public UserError ReportedError { get; protected set; }
}
/// <summary>
/// RecoveryCommand is a straightforward implementation of a recovery
/// command - this class represents a command presented to the user
/// (usually in the form of a button) that will help resolve or mitigate a
/// UserError.
/// </summary>
public class RecoveryCommand : ReactiveCommand, IRecoveryCommand
{
public bool IsDefault { get; set; }
public bool IsCancel { get; set; }
public string CommandName { get; protected set; }
public RecoveryOptionResult? RecoveryResult { get; set; }
/// <summary>
/// Constructs a RecoveryCommand.
/// </summary>
/// <param name="commandName">The user-visible name of this Command.</param>
/// <param name="handler">A convenience handler - equivalent to
/// Subscribing to the command and setting the RecoveryResult.</param>
public RecoveryCommand(string commandName, Func<object, RecoveryOptionResult> handler = null)
{
CommandName = commandName;
if (handler != null) {
this.Subscribe(x => RecoveryResult = handler(x));
}
}
/// <summary>
/// A default command whose caption is "Ok"
/// </summary>
/// <value>RetryOperation</value>
public static IRecoveryCommand Ok {
get { var ret = new RecoveryCommand("Ok") { IsDefault = true }; ret.Subscribe(_ => ret.RecoveryResult = RecoveryOptionResult.RetryOperation); return ret; }
}
/// <summary>
/// A default command whose caption is "Cancel"
/// </summary>
/// <value>FailOperation</value>
public static IRecoveryCommand Cancel {
get { var ret = new RecoveryCommand("Cancel") { IsCancel = true }; ret.Subscribe(_ => ret.RecoveryResult = RecoveryOptionResult.FailOperation); return ret; }
}
/// <summary>
/// A default command whose caption is "Yes"
/// </summary>
/// <value>RetryOperation</value>
public static IRecoveryCommand Yes {
get { var ret = new RecoveryCommand("Yes") { IsDefault = true }; ret.Subscribe(_ => ret.RecoveryResult = RecoveryOptionResult.RetryOperation); return ret; }
}
/// <summary>
/// A default command whose caption is "No"
/// </summary>
/// <value>FailOperation</value>
public static IRecoveryCommand No {
get { var ret = new RecoveryCommand("No") { IsCancel = true }; ret.Subscribe(_ => ret.RecoveryResult = RecoveryOptionResult.FailOperation); return ret; }
}
}
}
// vim: tw=120 ts=4 sw=4 et :