Skip to content

Commit

Permalink
db: document isDbError() (#7491)
Browse files Browse the repository at this point in the history
* feat: document isDbError()

* edit: forgot this ain't .astro

Co-authored-by: Sarah Rainsberger <[email protected]>

* edit: be expressive

Co-authored-by: Sarah Rainsberger <[email protected]>

---------

Co-authored-by: Sarah Rainsberger <[email protected]>
  • Loading branch information
bholmesdev and sarah11918 authored Mar 20, 2024
1 parent 3193d5c commit 2e4895d
Showing 1 changed file with 27 additions and 0 deletions.
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 });
};
```

0 comments on commit 2e4895d

Please sign in to comment.