Allow commands to return a Task<RuntimeResult> (#466)
* Allow commands to return a Task<RuntimeResult>
This allows bot developers to centralize command result logic by
using result data whether the command as successful or not.
Example usage:
```csharp
var _result = await Commands.ExecuteAsync(context, argPos);
if (_result is RuntimeResult result)
{
await message.Channel.SendMessageAsync(result.Reason);
}
else if (!_result.IsSuccess)
{
// Previous error handling
}
```
The RuntimeResult class can be subclassed too, for example:
```csharp
var _result = await Commands.ExecuteAsync(context, argPos);
if (_result is MySubclassedResult result)
{
var builder = new EmbedBuilder();
for (var pair in result.Data)
{
builder.AddField(pair.Key, pair.Value, true);
}
await message.Channel.SendMessageAsync("", embed: builder);
}
else if (_result is RuntimeResult result)
{
await message.Channel.SendMessageAsync(result.Reason);
}
else if (!_result.IsSuccess)
{
// Previous error handling
}
```
* Make RuntimeResult's ctor protected
* Make RuntimeResult abstract
It never really made sense to have it instantiable in the first place,
frankly.
This commit is contained in:
committed by
RogueException
parent
b96748f9c3
commit
74f6a4b392
27
src/Discord.Net.Commands/Results/RuntimeResult.cs
Normal file
27
src/Discord.Net.Commands/Results/RuntimeResult.cs
Normal file
@@ -0,0 +1,27 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
|
||||
namespace Discord.Commands
|
||||
{
|
||||
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
|
||||
public abstract class RuntimeResult : IResult
|
||||
{
|
||||
protected RuntimeResult(CommandError? error, string reason)
|
||||
{
|
||||
Error = error;
|
||||
Reason = reason;
|
||||
}
|
||||
|
||||
public CommandError? Error { get; }
|
||||
public string Reason { get; }
|
||||
|
||||
public bool IsSuccess => !Error.HasValue;
|
||||
|
||||
string IResult.ErrorReason => Reason;
|
||||
|
||||
public override string ToString() => Reason ?? (IsSuccess ? "Successful" : "Unsuccessful");
|
||||
private string DebuggerDisplay => IsSuccess ? $"Success: {Reason ?? "No Reason"}" : $"{Error}: {Reason}";
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user