Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

db: document isDbError() #7491

Merged
merged 3 commits into from
Mar 20, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/content/docs/en/guides/integrations-guide/db.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -221,3 +221,30 @@ Execute a `.ts` or `.js` file to read or write to your database. This accepts a
- `--remote` Run against your Studio project database. Omit to run against your development server.

Execute a raw SQL query against your database. Use the `--remote` flag to run against your Studio project database, or omit the flag to run against your development server.

## Astro DB utility reference

### `isDbError()`

The `isDbError()` function checks if an error is a libSQL database exception. This may include a foreign key constraint error when using references, or missing fields when inserting data. You can combine `isDbError()` with a try / catch block to handle database errors in your application:

```ts title="src/pages/api/comment/[id].ts" "idDbError"
import { db, Comment, isDbError } from 'astro:db';
import type { APIRoute } from 'astro';

export const POST: APIRoute = (ctx) => {
try {
await db.insert(Comment).values({
id: ctx.params.id,
content: 'Hello, world!'
});
} catch (e) {
if (isDbError(e)) {
return new Response(`Cannot insert comment with id ${id}\n\n${e.message}`, { status: 400 });
}
return new Response('An unexpected error occurred', { status: 500 });
}

return new Response(null, { status: 201 });
};
```
Loading