Skip to content

Commit

Permalink
enable optional stacktrace printing. throw runtime/commandrun errors …
Browse files Browse the repository at this point in the history
…upwards
  • Loading branch information
gschueler committed Oct 19, 2017
1 parent 02ce072 commit 39bd817
Showing 1 changed file with 32 additions and 3 deletions.
35 changes: 32 additions & 3 deletions toolbelt/src/main/java/com/simplifyops/toolbelt/ToolBelt.java
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,7 @@ public ToolBelt bannerResource(String resource) {
private static class CommandContext {
private CommandInput inputParser;
private CommandOutput output;
private boolean printStackTrace;


CommandInput getInputParser() {
Expand All @@ -257,6 +258,14 @@ void setInputParser(CommandInput inputParser) {
public void setOutput(CommandOutput output) {
this.output = output;
}

public boolean isPrintStackTrace() {
return printStackTrace;
}

public void setPrintStackTrace(boolean printStackTrace) {
this.printStackTrace = printStackTrace;
}
}

private static class CommandSet implements Tool, CommandInvoker {
Expand All @@ -271,6 +280,7 @@ private static class CommandSet implements Tool, CommandInvoker {
Tool other;
private boolean showBanner;
Supplier<String> banner;
Supplier<Boolean> printStackTrace;
public boolean hidden;

CommandSet(String name) {
Expand Down Expand Up @@ -325,9 +335,11 @@ public boolean runMain(final String[] args, final boolean exitSystem) {
} catch (CommandRunFailure commandRunFailure) {
context.getOutput().error(commandRunFailure.getMessage());
//verbose
StringWriter sb = new StringWriter();
commandRunFailure.printStackTrace(new PrintWriter(sb));
context.getOutput().error(sb.toString());
if (printStackTrace == null || printStackTrace.get()) {
StringWriter sb = new StringWriter();
commandRunFailure.printStackTrace(new PrintWriter(sb));
context.getOutput().error(sb.toString());
}
}
if (!result && exitSystem) {
System.exit(2);
Expand Down Expand Up @@ -666,6 +678,17 @@ public ToolBelt commandInput(CommandInput input) {
return this;
}

/**
* Enable or disable stacktrace printing on error
*
* @param printStackTrace true to print stack traces (default)
*
* @return this
*/
public ToolBelt printStackTrace(boolean printStackTrace) {
commands.printStackTrace = () -> printStackTrace;
return this;
}

/**
* Build the Tool
Expand Down Expand Up @@ -784,6 +807,12 @@ public boolean run(String[] args) throws CommandRunFailure, InputError {
if (e.getCause() instanceof InputError) {
throw (InputError) e.getCause();
}
if (e.getCause() instanceof RuntimeException) {
throw (RuntimeException) e.getCause();
}
if (e.getCause() instanceof CommandRunFailure) {
throw (CommandRunFailure) e.getCause();
}
e.getCause().printStackTrace();
} else {
e.printStackTrace();
Expand Down

0 comments on commit 39bd817

Please sign in to comment.