Skip to content

Debug D1

D1 allows you to capture exceptions and log errors returned when querying a database. To debug D1, you will use the same tools available when debugging Workers.

Handle errors

The D1 Workers Binding API returns detailed error messages within an Error object.

To ensure you are capturing the full error message, log or return e.message as follows:

try {
await db.exec("INSERTZ INTO my_table (name, employees) VALUES ()");
} catch (e: any) {
console.error({
message: e.message
});
}
/*
{
"message": "D1_EXEC_ERROR: Error in line 1: INSERTZ INTO my_table (name, employees) VALUES (): sql error: near \"INSERTZ\": syntax error in INSERTZ INTO my_table (name, employees) VALUES () at offset 0"
}
*/

Errors

The stmt. and db. methods throw an Error object whenever an error occurs.

To capture exceptions, log the Error.message value. For example, the code below has a query with an invalid keyword - INSERTZ instead of INSERT:

try {
// This is an intentional mispelling
await db.exec("INSERTZ INTO my_table (name, employees) VALUES ()");
} catch (e: any) {
console.error({
message: e.message
});
}

The code above throws the following error message:

{
"message": "D1_EXEC_ERROR: Error in line 1: INSERTZ INTO my_table (name, employees) VALUES (): sql error: near \"INSERTZ\": syntax error in INSERTZ INTO my_table (name, employees) VALUES () at offset 0"
}

Error list

D1 returns the following error constants, in addition to the extended (detailed) error message:

MessageCause
D1_ERRORGeneric error.
D1_TYPE_ERRORReturned when there is a mismatch in the type between a column and a value. A common cause is supplying an undefined variable (unsupported) instead of null.
D1_COLUMN_NOTFOUNDColumn not found.
D1_DUMP_ERRORDatabase dump error.
D1_EXEC_ERRORExec error in line x: y error.

View logs

View a stream of live logs from your Worker by using wrangler tail or via the Cloudflare dashboard.

Report issues

You should include as much of the following in any bug report:

  • The ID of your database. Use wrangler d1 list to match a database name to its ID.
  • The query (or queries) you ran when you encountered an issue. Ensure you redact any personally identifying information (PII).
  • The Worker code that makes the query, including any calls to bind() using the Workers Binding API.
  • The full error text, including the content of error.cause.message.