GH-3884: Throw clear exception when tool parameter receives blank or empty string from model
What
When a model returns a blank or empty string for a numeric tool parameter (Byte, Short, Integer, Long, Float, Double), JsonParser.toTypedObject() previously threw a cryptic NumberFormatException with no context about what went wrong.
Why
The fix adds an early blank-string guard via a private isStrictNumericType() helper that fires before any type-specific branch. Boolean and enum are intentionally excluded: Boolean.parseBoolean("") returns false by contract, and Enum.valueOf already throws IllegalArgumentException with a descriptive message. Primitive types (int, long, etc.) are covered automatically via ClassUtils.resolvePrimitiveIfNecessary.
Changes
JsonParser— addedisStrictNumericType()helper and blank-string guard intoTypedObject(); updated@throwsJavadocJsonParserTests— 9 new tests covering all 6 numeric types (empty and blank string), primitive type pass-through,Booleanreturningfalse, andenumthrowing its own exception
Fixes GH-3884 (https://github.com/spring-projects/spring-ai/issues/3884)
Fix works. I verified it locally and the unit tests in JsonParserTests all pass. However, one suggestion would be to add a test at the MethodToolCallback level too. Something like this:
@Test
void emptyStringForLongParamThrowsClearException() {
var callback = MethodToolCallbackProvider.builder()
.toolObjects(new IdTool())
.build()
.getToolCallbacks()[0];
String toolInput = """
{ "id": "" }
""";
assertThatThrownBy(() -> callback.call(toolInput))
.isInstanceOf(ToolExecutionException.class)
.hasRootCauseInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Cannot convert blank or empty string to numeric type 'Long'");
}
static class IdTool {
@Tool(description = "Lookup by id")
public String lookup(Long id) { return "id=" + id; }
}
@sdeleuze can you take a look on this PR?
Thanks for the suggestion! Added a MethodToolCallbackProvider-level test (emptyStringForLongParamThrowsClearException) in MethodToolCallbackProviderTests that exercises the full call path — provider → callback → JsonParser — and asserts that a ToolExecutionException wrapping an IllegalArgumentException with the expected message is thrown when an empty string is passed for a Long parameter.