Skip to content

Commit fcbf6e9

Browse files
Document onSqlError hook for customizable SQL error handling
Adds documentation for the new onSqlError hook that allows users to customize SQL error logging behavior. The hook is called when SQL queries fail, giving users full control over error handling and logging. Related to cloudflare/agents#768 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
1 parent 7f80f4b commit fcbf6e9

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

src/content/docs/agents/api-reference/agents-api.mdx

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -596,6 +596,56 @@ export class YourAgent extends Agent {
596596

597597
</TypeScriptExample>
598598

599+
#### SQL error handling
600+
601+
Handle SQL execution errors by overriding the `onSqlError` method. This allows you to customize logging behavior or implement error recovery strategies.
602+
603+
```ts
604+
// SQL error handling in the Agent class
605+
class Agent<Env, State = unknown> {
606+
// Called when a SQL query execution fails
607+
// Override this method to customize error logging or implement recovery logic
608+
onSqlError(query: string, error: unknown): void;
609+
}
610+
```
611+
612+
<TypeScriptExample>
613+
614+
```ts
615+
// Example of customizing SQL error handling
616+
export class YourAgent extends Agent {
617+
// Override onSqlError to customize error handling
618+
onSqlError(query: string, error: unknown): void {
619+
// Log to a custom logging service
620+
console.error(`SQL query failed: ${query}`, {
621+
error,
622+
timestamp: Date.now(),
623+
agentName: this.name,
624+
});
625+
626+
// You could also:
627+
// - Send errors to an external monitoring service
628+
// - Implement custom retry logic
629+
// - Filter sensitive information from logs
630+
}
631+
632+
async getUserById(id: string) {
633+
try {
634+
// If this query fails, onSqlError will be called before the error is thrown
635+
const users = this.sql<{ id: string; name: string }>`
636+
SELECT * FROM users WHERE id = ${id}
637+
`;
638+
return users[0];
639+
} catch (error) {
640+
// Handle the error after onSqlError has logged it
641+
return null;
642+
}
643+
}
644+
}
645+
```
646+
647+
</TypeScriptExample>
648+
599649
:::note
600650

601651
Visit the [state management API documentation](/agents/api-reference/store-and-sync-state/) within the Agents SDK, including the native `state` APIs and the built-in `this.sql` API for storing and querying data within your Agents.

0 commit comments

Comments
 (0)