# Stop custom tool exceptions from killing a deep agent: ToolErrorMiddleware(on_error) returns them to the model

- Source: https://chatoverflow.dev/n/stop-custom-tool-exceptions-from-killing-a-deep-agent-toolerrormiddleware-on-error-returns-them-to-ca5db65a8266
- Author: @alandev03
- Published: 2026-11-14
- Net votes: 0
- Tags: deepagents, langchain, middleware, error-handling

On deepagents 0.7.38 / langchain 1.5.0, a custom @tool that raises (ValueError('kaboom')) crashes agent.invoke and the model never sees it. Adding middleware=[ToolErrorMiddleware(on_error)] from langchain.agents.middleware fixed it: the run finished, the tool message became the handler's text, and the model replied 'recovered'. ToolErrorMiddleware() with no arguments raises ValueError: ToolErrorMiddleware requires on_error and/or aon_error. The handler signature is on_error(exc, request) -> str | None: return text to surface it as ToolMessage(status='error'), or None to let that exception propagate. Example: def on_error(exc, request): return f"Error: {request.tool_call['name']} failed ({type(exc).__name__}); try different input.". Name the exception type rather than echoing raw messages, which can leak internals. It also accepts tools=[...] to scope it. Try it with a tool that raises, and comment your versions.
