Skip to content

Commit 040f03b

Browse files
committed
Fix error message formatting when using the bean validation API with command options
Resolves #1100
1 parent 30531c8 commit 040f03b

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

spring-shell-core/src/main/java/org/springframework/shell/result/ParameterValidationExceptionResultHandler.java

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2017-2022 the original author or authors.
2+
* Copyright 2017-2025 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -15,6 +15,8 @@
1515
*/
1616
package org.springframework.shell.result;
1717

18+
import jakarta.validation.Path;
19+
1820
import org.jline.terminal.Terminal;
1921
import org.jline.utils.AttributedString;
2022
import org.jline.utils.AttributedStyle;
@@ -26,6 +28,7 @@
2628
*
2729
* @author Eric Bottard
2830
* @author Janne Valkealahti
31+
* @author Mahmoud Ben Hassine
2932
*/
3033
public class ParameterValidationExceptionResultHandler
3134
extends TerminalAwareResultHandler<ParameterValidationException> {
@@ -39,10 +42,19 @@ protected void doHandleResult(ParameterValidationException result) {
3942
terminal.writer().println(new AttributedString("The following constraints were not met:",
4043
AttributedStyle.DEFAULT.foreground(AttributedStyle.RED)).toAnsi());
4144
result.getConstraintViolations().stream()
42-
.forEach(v -> {
43-
terminal.writer().println(new AttributedString(v.toString(),
45+
.forEach(violation -> {
46+
Path propertyPath = violation.getPropertyPath();
47+
String violationMessage = violation.getMessage();
48+
String errorMessage = String.format("\t--%s: %s", extractPropertyName(propertyPath), violationMessage);
49+
terminal.writer().println(new AttributedString(errorMessage,
4450
AttributedStyle.DEFAULT.foreground(AttributedStyle.RED)).toAnsi(terminal));
4551
});
4652
}
4753

54+
private String extractPropertyName(Path propertyPath) {
55+
String path = propertyPath.toString();
56+
int lastIndexOfDot = path.lastIndexOf(".");
57+
return lastIndexOfDot == -1 ? path : path.substring(lastIndexOfDot + 1);
58+
}
59+
4860
}

spring-shell-docs/modules/ROOT/pages/options/validation.adoc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,5 +20,5 @@ From the preceding example, you get the following behavior for free:
2020
----
2121
shell:>change-password hello
2222
The following constraints were not met:
23-
--password string : size must be between 8 and 40 (You passed 'hello')
23+
--password : size must be between 8 and 40 (You passed 'hello')
2424
----

0 commit comments

Comments
 (0)