langchain - 💡(How to fix) Fix @wrap_tool_call middleware could allow to catch exceptions and turn them into ToolException [1 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
langchain-ai/langchain#37195Fetched 2026-05-06 06:14:45
View on GitHub
Comments
0
Participants
1
Timeline
5
Reactions
0
Participants
Timeline (top)
labeled ×4issue_type_added ×1

Error Message

from zipfile import BadZipFile

from langchain.agents.middleware import wrap_tool_call from langchain.tools import ToolException

@wrap_tool_call def HandleFileErrorsMiddleware(request, handler): """ Catch common exceptions related to opening common types of files Transforms them in strings so the agent can react to them For more exotic exception, use specialized middlewares """ try: handler(request) except (FileNotFoundError, NotADirectoryError, BadZipFile) as err: # Accourding to documentation, tool exception doesn't stop an agent from running raise ToolException(err)

Root Cause

Though the syntax of the code above is what I would aim with this feature request, it doesn't behave as expected. The ToolException error is raised outside of the tools "handler" function and not inside, so somehow it's not caught. When running this code with agent.stream for example, the agent will crash because it doesn't catch ToolException higher up.

Code Example

from zipfile import BadZipFile

from langchain.agents.middleware import wrap_tool_call
from langchain.tools import ToolException


@wrap_tool_call
def HandleFileErrorsMiddleware(request, handler):
    """
    Catch common exceptions related to opening common types of files
    Transforms them in strings so the agent can react to them
    For more exotic exception, use specialized middlewares
    """
    try:
        handler(request)
    except (FileNotFoundError, NotADirectoryError, BadZipFile) as err:
        # Accourding to documentation, tool exception doesn't stop an agent from running
        raise ToolException(err)
RAW_BUFFERClick to expand / collapse

Submission checklist

  • This is a feature request, not a bug report or usage question.
  • I added a clear and descriptive title that summarizes the feature request.
  • I used the GitHub search to find a similar feature request and didn't find it.
  • I checked the LangChain documentation and API reference to see if this feature already exists.
  • This is not related to the langchain-community package.

Package (Required)

  • langchain
  • langchain-openai
  • langchain-anthropic
  • langchain-classic
  • langchain-core
  • langchain-model-profiles
  • langchain-tests
  • langchain-text-splitters
  • langchain-chroma
  • langchain-deepseek
  • langchain-exa
  • langchain-fireworks
  • langchain-groq
  • langchain-huggingface
  • langchain-mistralai
  • langchain-nomic
  • langchain-ollama
  • langchain-openrouter
  • langchain-perplexity
  • langchain-qdrant
  • langchain-xai
  • Other / not sure / general

Feature Description

I would like a better way to handle common exceptions in tools, such as FileNotFoundException.

Use Case

I am writing tools that runs common low-level operations such as opening files. I'd like to setup exception management at agent-level (and not tool-level) for these common operations. This would simplify tool implementation for trivial operations.

Proposed Solution

@wrap_tool_call middleware should allow raising ToolException errors that are caught as describe in the documentation, not failing the tool but instead sending the error text back to the agent for processing.

from zipfile import BadZipFile

from langchain.agents.middleware import wrap_tool_call
from langchain.tools import ToolException


@wrap_tool_call
def HandleFileErrorsMiddleware(request, handler):
    """
    Catch common exceptions related to opening common types of files
    Transforms them in strings so the agent can react to them
    For more exotic exception, use specialized middlewares
    """
    try:
        handler(request)
    except (FileNotFoundError, NotADirectoryError, BadZipFile) as err:
        # Accourding to documentation, tool exception doesn't stop an agent from running
        raise ToolException(err)

Alternatives Considered

Though the syntax of the code above is what I would aim with this feature request, it doesn't behave as expected. The ToolException error is raised outside of the tools "handler" function and not inside, so somehow it's not caught. When running this code with agent.stream for example, the agent will crash because it doesn't catch ToolException higher up.

I found out nested in a migration documentation here an example of outputting a "ToolMessage" rather than reraising a ToolException. it should do the job for now but it's not the best developer experience, I would have expected ToolException to work. Also the code demo comments actually advocates against what I am doing here, yet I don't see an issue with handling low level issues at agent level, a file not found doesn't necessarily need to bubble up outside the agent loop for instance, that would be pretty annoying for administrative tasks and such.

Also, handle_tool_error is documented for ToolNode but doesn't seem to work for the @tool decorator.

Additional Context

Handling errors is a common beginner grip with agents: you are expected to return string errors and not raises. But currently LangChain API is a bit flimsy regarding error managements, unless I've missed some relevant APIs.

Related forum post, dealing with return_direct: https://forum.langchain.com/t/handling-exceptions-in-tool-with-return-direct-true/2425 Previous issue: https://github.com/langchain-ai/langchain/issues/10528

extent analysis

TL;DR

Implement a middleware to catch common exceptions and return a ToolMessage instead of raising a ToolException to handle errors at the agent level.

Guidance

  • Review the LangChain documentation on error handling and ToolMessage to understand the recommended approach for handling tool errors.
  • Consider using the handle_tool_error method for ToolNode as a potential solution, although it may not work with the @tool decorator.
  • Modify the HandleFileErrorsMiddleware to return a ToolMessage with the error text instead of raising a ToolException.
  • Investigate the return_direct parameter and its relation to error handling in tools.

Example

from langchain.tools import ToolMessage

@wrap_tool_call
def HandleFileErrorsMiddleware(request, handler):
    try:
        handler(request)
    except (FileNotFoundError, NotADirectoryError, BadZipFile) as err:
        return ToolMessage(f"Error: {str(err)}")

Notes

The current implementation of ToolException may not work as expected when raised outside of the tool's "handler" function. The ToolMessage approach may be a more reliable solution for handling errors at the agent level.

Recommendation

Apply the workaround of returning a ToolMessage with the error text instead of raising a ToolException, as it is a more reliable and documented approach for handling tool errors in LangChain.

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING

langchain - 💡(How to fix) Fix @wrap_tool_call middleware could allow to catch exceptions and turn them into ToolException [1 participants]