Error Handling
Last updated on
10 August 2023
The Database API throws exceptions on error, which can be picked up by wrapping your database operations in try {} catch() {} blocks, as shown in this example:
// The transaction opens here.
$txn = $connection->startTransaction();
try {
$id = $connection->insert('example')
->fields([
'field1' => 'mystring',
'field2' => 5,
])
->execute();
my_other_function($id);
return $id;
}
catch (\Exception $e) {
// Something went wrong somewhere, so roll back now.
$txn->rollBack();
// Log the exception to watchdog.
\Drupal::logger('type')->error($e->getMessage());
}Help improve this page
Page status: No known problems
You can:
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion
Still on Drupal 7? Security support for Drupal 7 ended on 5 January 2025. Please visit our Drupal 7 End of Life resources page to review all of your options.