@@ -396,36 +396,51 @@ The `tools` argument to `createAgent` accepts:
396396- LangChain tool instances
397397- Objects that represent built-in provider tools
398398
399- Use middleware ` wrapToolCall ` to centralize error handling and logging for tools.
399+ #### Handling tool errors
400+
401+ You can now configure the handling of tool errors with middleware implementing the ` wrapToolCall ` method.
400402
401403<CodeGroup >
402404``` typescript v1 (new)
403- import { createAgent , createMiddleware } from " langchain" ;
405+ import { createAgent , createMiddleware , ToolMessage } from " langchain" ;
404406
405- const errorHandling = createMiddleware ({
406- name: " ToolErrors " ,
407+ const handleToolErrors = createMiddleware ({
408+ name: " HandleToolErrors " ,
407409 wrapToolCall : async (request , handler ) => {
408410 try {
409411 return await handler (request );
410- } catch (err ) {
411- return ` Error executing ${request .toolName }: ${String (err )} ` ;
412+ } catch (error ) {
413+ // Only handle errors that occur during tool execution due to invalid inputs
414+ // that pass schema validation but fail at runtime (e.g., invalid SQL syntax).
415+ // Do NOT handle:
416+ // - Network failures (use tool retry middleware instead)
417+ // - Incorrect tool implementation errors (should bubble up)
418+ // - Schema mismatch errors (already auto-handled by the framework)
419+ //
420+ // Return a custom error message to the model
421+ return new ToolMessage ({
422+ content: ` Tool error: Please check your input and try again. (${error }) ` ,
423+ tool_call_id: request .toolCall .id ! ,
424+ });
412425 }
413426 },
414427});
415428
416429const agent = createAgent ({
417430 model: " claude-sonnet-4-5-20250929" ,
418431 tools: [checkWeather , searchWeb ],
419- middleware: [errorHandling ],
432+ middleware: [handleToolErrors ],
420433});
421434```
422435``` typescript v0 (old)
423- import { createReactAgent } from " @langchain/langgraph/prebuilts" ;
436+ import { createReactAgent , ToolNode } from " @langchain/langgraph/prebuilts" ;
424437
425438const agent = createReactAgent ({
426439 model: " claude-sonnet-4-5-20250929" ,
427- tools: [checkWeather , searchWeb ],
428- // Error handling commonly implemented inside tool code or post hooks
440+ tools: new ToolNode (
441+ [checkWeather , searchWeb ],
442+ { handleToolErrors: true } // [!code highlight]
443+ ),
429444});
430445```
431446</CodeGroup >
0 commit comments