Error handling

Last updated on
3 November 2016

Drupal 7 will no longer be supported after January 5, 2025. Learn more and find resources for Drupal 7 sites

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 = db_transaction();
try {
    $id = db_insert('example')
      ->fields(array(
        '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.
    watchdog_exception('type', $e);
  }

Source: http://api.drupal.org/api/group/database/7.

Help improve this page

Page status: No known problems

You can: