Skip to content

Commit f54faba

Browse files
committed
Merge pull request #33669 from Seungpang
* pr/33669: Polish "Reject empty strings in DurationFormatterUtils" Reject empty strings in DurationFormatterUtils Closes gh-33669
2 parents 7f7f65c + e2238c0 commit f54faba

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

spring-context/src/main/java/org/springframework/format/datetime/standard/DurationFormatterUtils.java

+2-1
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ public static Duration parse(String value, DurationFormat.Style style) {
6262
* @return a duration
6363
*/
6464
public static Duration parse(String value, DurationFormat.Style style, @Nullable DurationFormat.Unit unit) {
65+
Assert.hasText(value, () -> "Value must not be empty");
6566
return switch (style) {
6667
case ISO8601 -> parseIso8601(value);
6768
case SIMPLE -> parseSimple(value, unit);
@@ -149,7 +150,7 @@ private static Duration parseIso8601(String value) {
149150
try {
150151
return Duration.parse(value);
151152
}
152-
catch (Throwable ex) {
153+
catch (Exception ex) {
153154
throw new IllegalArgumentException("'" + value + "' is not a valid ISO-8601 duration", ex);
154155
}
155156
}

spring-context/src/test/java/org/springframework/format/datetime/standard/DurationFormatterUtilsTests.java

+19
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,10 @@
2323

2424
import org.junit.jupiter.api.Nested;
2525
import org.junit.jupiter.api.Test;
26+
import org.junit.jupiter.params.ParameterizedTest;
27+
import org.junit.jupiter.params.provider.EnumSource;
2628

29+
import org.springframework.format.annotation.DurationFormat;
2730
import org.springframework.format.annotation.DurationFormat.Unit;
2831

2932
import static org.assertj.core.api.Assertions.assertThat;
@@ -38,6 +41,22 @@
3841
*/
3942
class DurationFormatterUtilsTests {
4043

44+
@ParameterizedTest
45+
@EnumSource(DurationFormat.Style.class)
46+
void parseEmptyStringFailsWithDedicatedException(DurationFormat.Style style) {
47+
assertThatIllegalArgumentException()
48+
.isThrownBy(() -> DurationFormatterUtils.parse("", style))
49+
.withMessage("Value must not be empty");
50+
}
51+
52+
@ParameterizedTest
53+
@EnumSource(DurationFormat.Style.class)
54+
void parseNullStringFailsWithDedicatedException(DurationFormat.Style style) {
55+
assertThatIllegalArgumentException()
56+
.isThrownBy(() -> DurationFormatterUtils.parse(null, style))
57+
.withMessage("Value must not be empty");
58+
}
59+
4160
@Test
4261
void parseSimpleWithUnits() {
4362
Duration nanos = DurationFormatterUtils.parse("1ns", SIMPLE, Unit.SECONDS);

0 commit comments

Comments
 (0)