Skip to content

Commit

Permalink
Polish DataBinder.
Browse files Browse the repository at this point in the history
Use IllegalArgumentException instead of NumberFormatException.

gh-34305.

Signed-off-by: Mengqi Xu <2663479778@qq.com>
  • Loading branch information
remeio committed Jan 22, 2025
1 parent b3e8882 commit 1d83df9
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@
* @author Stephane Nicoll
* @author Kazuki Shimizu
* @author Sam Brannen
* @author Mengqi Xu
* @see #setAllowedFields
* @see #setRequiredFields
* @see #registerCustomEditor
Expand Down Expand Up @@ -1087,7 +1088,13 @@ private boolean hasValuesFor(String paramPath, ValueResolver resolver) {
if (name.startsWith(paramPath + "[")) {
int endIndex = name.indexOf(']', paramPath.length() + 1);
String rawIndex = name.substring(paramPath.length() + 1, endIndex);
int index = Integer.parseInt(rawIndex);
int index;
try {
index = Integer.parseInt(rawIndex);
}
catch (NumberFormatException ex) {
throw new IllegalArgumentException("Failed to parse index from '" + rawIndex + "'", ex);
}
indexes = (indexes != null ? indexes : new TreeSet<>());
indexes.add(index);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,13 @@
import org.springframework.web.testfixture.servlet.MockHttpServletRequest;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

/**
* Test fixture for {@link ExtendedServletRequestDataBinder}.
*
* @author Rossen Stoyanchev
* @author Mengqi Xu
*/
class ExtendedServletRequestDataBinderTests {

Expand Down Expand Up @@ -90,6 +92,19 @@ void createBinderViaConstructor() {
assertThat(bean.someIntArray()).containsExactly(1, 2);
}

@Test // gh-34205
void createBinderViaConstructorWithInvalidIndex() {
request.addParameter("Some-Int-Array[foo]", "1");

ServletRequestDataBinder binder = new ExtendedServletRequestDataBinder(null);
binder.setTargetType(ResolvableType.forClass(DataBean.class));
binder.setNameResolver(new BindParamNameResolver());

assertThatThrownBy(() -> binder.construct(request))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Failed to parse index from 'foo'");
}

@Test
void uriVarsAndHeadersAddedConditionally() {
request.addParameter("name", "John");
Expand Down

0 comments on commit 1d83df9

Please sign in to comment.