Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add TypeResolver to ExceptionHandler (OPTION #2) #1326

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/Spectre.Console.Cli/CommandApp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ public sealed class CommandApp : ICommandApp
{
private readonly Configurator _configurator;
private readonly CommandExecutor _executor;
private ITypeRegistrar _registrar;
private bool _executed;

/// <summary>
Expand All @@ -21,6 +22,7 @@ public CommandApp(ITypeRegistrar? registrar = null)

_configurator = new Configurator(registrar);
_executor = new CommandExecutor(registrar);
_registrar = registrar;
}

/// <summary>
Expand Down Expand Up @@ -102,7 +104,8 @@ public async Task<int> RunAsync(IEnumerable<string> args)

if (_configurator.Settings.ExceptionHandler != null)
{
return _configurator.Settings.ExceptionHandler(ex);
using var resolver = new TypeResolverAdapter(_registrar.Build());
return _configurator.Settings.ExceptionHandler(ex, resolver);
}

// Render the exception.
Expand Down
13 changes: 12 additions & 1 deletion src/Spectre.Console.Cli/ConfiguratorExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -359,7 +359,7 @@ public static IConfigurator SetExceptionHandler(this IConfigurator configurator,
/// <param name="configurator">The configurator.</param>
/// <param name="exceptionHandler">The Action that handles the exception.</param>
/// <returns>A configurator that can be used to configure the application further.</returns>
public static IConfigurator SetExceptionHandler(this IConfigurator configurator, Func<Exception, int>? exceptionHandler)
public static IConfigurator SetExceptionHandler(this IConfigurator configurator, Func<Exception, ITypeResolver, int>? exceptionHandler)
{
if (configurator == null)
{
Expand All @@ -369,4 +369,15 @@ public static IConfigurator SetExceptionHandler(this IConfigurator configurator,
configurator.Settings.ExceptionHandler = exceptionHandler;
return configurator;
}

/// <summary>
/// Sets the ExceptionsHandler.
/// </summary>
/// <param name="configurator">The configurator.</param>
/// <param name="exceptionHandler">The Action that handles the exception.</param>
/// <returns>A configurator that can be used to configure the application further.</returns>
public static IConfigurator SetExceptionHandler(this IConfigurator configurator, Func<Exception, int>? exceptionHandler)
{
return configurator.SetExceptionHandler(exceptionHandler == null ? null : (ex, _) => exceptionHandler(ex));
}
}
2 changes: 1 addition & 1 deletion src/Spectre.Console.Cli/ICommandAppSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,5 +80,5 @@ public interface ICommandAppSettings
/// Gets or sets a handler for Exceptions.
/// <para>This handler will not be called, if <see cref="PropagateExceptions"/> is set to <c>true</c>.</para>
/// </summary>
public Func<Exception, int>? ExceptionHandler { get; set; }
public Func<Exception, ITypeResolver, int>? ExceptionHandler { get; set; }
}
78 changes: 45 additions & 33 deletions src/Spectre.Console.Cli/Internal/CommandExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,41 +49,53 @@ public async Task<int> Execute(IConfiguration configuration, IEnumerable<string>

// Create the resolver.
using (var resolver = new TypeResolverAdapter(_registrar.Build()))
{
// Get the registered help provider, falling back to the default provider
// registered above if no custom implementations have been registered.
var helpProvider = resolver.Resolve(typeof(IHelpProvider)) as IHelpProvider ?? defaultHelpProvider;

// Currently the root?
if (parsedResult?.Tree == null)
{
// Display help.
configuration.Settings.Console.SafeRender(helpProvider.Write(model, null));
return 0;
}

// Get the command to execute.
var leaf = parsedResult.Tree.GetLeafCommand();
if (leaf.Command.IsBranch || leaf.ShowHelp)
{
// Branches can't be executed. Show help.
configuration.Settings.Console.SafeRender(helpProvider.Write(model, leaf.Command));
return leaf.ShowHelp ? 0 : 1;
}

// Is this the default and is it called without arguments when there are required arguments?
if (leaf.Command.IsDefaultCommand && args.Count() == 0 && leaf.Command.Parameters.Any(p => p.Required))
{
// Display help for default command.
configuration.Settings.Console.SafeRender(helpProvider.Write(model, leaf.Command));
return 1;
}
{
try
{
// Get the registered help provider, falling back to the default provider
// registered above if no custom implementations have been registered.
var helpProvider = resolver.Resolve(typeof(IHelpProvider)) as IHelpProvider ?? defaultHelpProvider;

// Currently the root?
if (parsedResult?.Tree == null)
{
// Display help.
configuration.Settings.Console.SafeRender(helpProvider.Write(model, null));
return 0;
}

// Get the command to execute.
var leaf = parsedResult.Tree.GetLeafCommand();
if (leaf.Command.IsBranch || leaf.ShowHelp)
{
// Branches can't be executed. Show help.
configuration.Settings.Console.SafeRender(helpProvider.Write(model, leaf.Command));
return leaf.ShowHelp ? 0 : 1;
}

// Is this the default and is it called without arguments when there are required arguments?
if (leaf.Command.IsDefaultCommand && args.Count() == 0 && leaf.Command.Parameters.Any(p => p.Required))
{
// Display help for default command.
configuration.Settings.Console.SafeRender(helpProvider.Write(model, leaf.Command));
return 1;
}

// Create the content.
var context = new CommandContext(parsedResult.Remaining, leaf.Command.Name, leaf.Command.Data);
// Create the content.
var context = new CommandContext(parsedResult.Remaining, leaf.Command.Name, leaf.Command.Data);

// Execute the command tree.
return await Execute(leaf, parsedResult.Tree, context, resolver, configuration).ConfigureAwait(false);
// Execute the command tree.
return await Execute(leaf, parsedResult.Tree, context, resolver, configuration).ConfigureAwait(false);
}
catch (Exception ex)
{
if (configuration.Settings.ExceptionHandler != null)
{
return configuration.Settings.ExceptionHandler(ex, resolver);
}

throw;
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ internal sealed class CommandAppSettings : ICommandAppSettings
public ParsingMode ParsingMode =>
StrictParsing ? ParsingMode.Strict : ParsingMode.Relaxed;

public Func<Exception, int>? ExceptionHandler { get; set; }
public Func<Exception, ITypeResolver, int>? ExceptionHandler { get; set; }

public CommandAppSettings(ITypeRegistrar registrar)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ namespace Spectre.Console.Tests.Data;

public sealed class ThrowingCommand : Command<ThrowingCommandSettings>
{
public const string Message = "W00t?";

public override int Execute(CommandContext context, ThrowingCommandSettings settings)
{
throw new InvalidOperationException("W00t?");
throw new InvalidOperationException(Message);
}
}
32 changes: 32 additions & 0 deletions test/Spectre.Console.Cli.Tests/Unit/CommandAppTests.Exceptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,5 +88,37 @@ public void Should_Handle_Exceptions_If_ExceptionHandler_Is_Set_Using_Function()
result.ExitCode.ShouldBe(-99);
exceptionHandled.ShouldBeTrue();
}

[Fact]
public void Should_Handle_Exceptions_If_ExceptionHandler_Is_Set_Using_Function_And_Logger_Is_Registered()
{
ITypeRegistrar registrar = new DefaultTypeRegistrar();

var loggerGlobal = new List<string>();
registrar.RegisterInstance(typeof(List<string>), loggerGlobal);

// Given
var app = new CommandAppTester(registrar);
app.Configure(config =>
{
config.AddCommand<ThrowingCommand>("throw");
config.SetExceptionHandler((ex, resolver) =>
{
var logger = resolver.Resolve(typeof(List<string>)) as List<string>;
logger.Add(ex.Message);
return -99;
});
});

// When
var result = app.Run(new[] { "throw" });

// Then
result.ExitCode.ShouldBe(-99);
loggerGlobal.ShouldBe(new[]
{
ThrowingCommand.Message,
});
}
}
}