Skip to content

Commit

Permalink
Keep original exception thrown by the parameter setter method
Browse files Browse the repository at this point in the history
This change adds the exception thrown by a setter method annotated with the
@parameter to the ParameterException.

Before this change it was not clear what exactly happened, because
ParameterException did not have the original exception thrown by
the @parameter setter method.
  • Loading branch information
sdruzkin authored and mkarg committed Dec 17, 2023
1 parent ec4b06c commit 086d7ba
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/main/java/com/beust/jcommander/Parameterized.java
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ public void set(Object object, Object value) {
if (ex.getTargetException() instanceof ParameterException) {
throw (ParameterException) ex.getTargetException();
} else {
throw new ParameterException(errorMessage(method, ex));
throw new ParameterException(errorMessage(method, ex), ex.getTargetException());
}
}
}
Expand Down
18 changes: 18 additions & 0 deletions src/test/java/com/beust/jcommander/MethodSetterTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,24 @@ public void setHost(String host) {
Assert.assertTrue(passed, "Should have thrown an exception");
}

public void setterThatThrowsKeepsOriginalException() {
class Arg {
@Parameter(names = "--host")
public void setHost(String host) {
throw new IllegalArgumentException("Illegal host");
}
}
boolean passed = false;
try {
JCommander.newBuilder().addObject(new Arg()).build().parse("--host", "host");
} catch(ParameterException ex) {
Assert.assertEquals(ex.getCause().getClass(), IllegalArgumentException.class);
Assert.assertEquals(ex.getCause().getMessage(), "Illegal host");
passed = true;
}
Assert.assertTrue(passed, "Should have thrown an exception");
}

public void getterReturningNonString() {
class Arg {
private Integer port;
Expand Down

0 comments on commit 086d7ba

Please sign in to comment.