ai icon indicating copy to clipboard operation
ai copied to clipboard

Unable to catch NoOutputGeneratedError

Open colecorrente opened this issue 1 year ago • 9 comments

Description

When NoOutputGeneratedError is thrown due to an api error such as Anthropic returning an error prompt is too long: 205138 tokens > 200000 maximum

NoOutputGeneratedError will be thrown, but cannot be caught.

 try {
        return streamText({
            model: anthropic("claude-sonnet-4-20250514"),
            stopWhen: stepCountIs(25),
            maxRetries: 2,
            tools,
            onError: ({error}) => {
                Logger.error("Agent onError", error); // <- Unable to reach this error
            },
        });
    } catch (e) {
        Logger.error("Agent error", e); // <- Unable to catch the error
    }

Appears to be introduced in 5.0.12

AI SDK Version

  • ai: 5.0.14

Code of Conduct

  • [x] I agree to follow this project's Code of Conduct

colecorrente avatar Aug 15 '25 19:08 colecorrente

You cannot catch errors like this because of the streaming, which immediately returns. Either use onError or scan the stream for error parts.

lgrammel avatar Aug 18 '25 07:08 lgrammel

If there is no way to catch the error, how do we prevent this error from being uncaught and crashing our service? My service crashes as a result of this unhandled exception and this is new in 5.0.12. As mentioned, that error does not appear in onError either. It end ups triggering uncaughtExceptionMonitor event handler in my node server.

colecorrente avatar Aug 18 '25 17:08 colecorrente

 try {
        const result =  streamText({
            model: anthropic("claude-sonnet-4-20250514"),
            stopWhen: stepCountIs(25),
            maxRetries: 2,
            tools,
            onError: ({error}) => {
                Logger.error("Agent onError", error); // <- Unable to reach this error
            },
        });

         result.consumeStream()

         result.pipeUIMessageStreamToResponse(res, {
                onError: (error) => {
                     Logger.error("Agent pipeUIMessageStreamToResponse", error); // <- Unable to reach this error
                },
            });
        },
    } catch (e) {
        Logger.error("Agent catch error", e); // <- Unable to catch the error
    }

More accurate example of my code provided here @lgrammel

colecorrente avatar Aug 18 '25 18:08 colecorrente

Promise.all([result.providerMetadata, result.usage, result.totalUsage]).then(
                ([providerMetadata, usage, totalUsage]) => {
                    Logger.debug(
                        JSON.stringify(
                            {
                                providerMetadata,
                                usage,
                                totalUsage,
                            },
                            null,
                            2
                        )
                    );
                }
            );

This code was my problem. This Promise.all was throwing. resolved

colecorrente avatar Aug 19 '25 17:08 colecorrente

@colecorrente why was Promise.all throwing? was any of the result.* calls throwing?

lgrammel avatar Aug 21 '25 07:08 lgrammel

I ended up using unhandledRejection to catch it

process.on('unhandledRejection', (reason, p) => {
  console.log('Unhandled Rejection at:', p, 'reason:', reason);
});

akinorimizushima avatar Aug 29 '25 09:08 akinorimizushima

I also encountered the same issue. When I interrupt the streaming output, a NoOutputGeneratedError is thrown, which directly terminates my Node process. Using try...catch cannot intercept it, and using onError does not catch the exception either.

Through testing, I found that this issue occurs when I write it like this:

const result = await streamText({
  model,
  tools,
  system: systemPrompt,
  messages: convertToModelMessages(messages),
});

result.totalUsage
.then((usage) => {
});

You must handle exceptions for this Promise:

const result = await streamText({
  model,
  tools,
  system: systemPrompt,
  messages: convertToModelMessages(messages),
});

result.totalUsage
.then((usage) => {
})
.catch((error) => {});

However, if I handle it in onFinish, the problem does not occur:

const result = await streamText({
  model,
  tools,
  system: systemPrompt,
  messages: convertToModelMessages(messages),
  onFinish: async (result) => {
    if (result.totalUsage) {
    }
  },
});

LIlGG avatar Sep 11 '25 10:09 LIlGG

@lgrammel you were wrong to close this, the reason this issue arises is because the user has absolutely no idea where the call site is that triggered the unhandled promise, due to the async (...) => promiseReturningFunction pattern being used all throughout the AI sdk code.

https://github.com/vercel/ai/issues/13838

Basically, you've removed all the debugging information from the library by using this pattern, and now people have no idea where the errors are originating from because the call site information has gone missing

mdierolf avatar Mar 26 '26 03:03 mdierolf

Identify issue type

Identified as None
Confidence: High

Rationale

This is primarily a support/debugging issue caused by unhandled rejected Promises rather than an established SDK defect. The later complaint about missing async call-site information points to a separate issue.

Evidence

  • The reporter determined that an unhandled rejection came from their Promise.all([result.providerMetadata, result.usage, result.totalUsage]) call and stated the issue was resolved.
  • Another commenter confirmed that result.totalUsage is a Promise whose rejection must be handled with .catch().
  • The synchronous try...catch cannot catch errors produced later by streaming or rejected result Promises.

lgrammel avatar Jul 22 '26 14:07 lgrammel