Documentation Level: 
Intermediate
Documentation Status: 
No known problems

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: https://docs.backdropcms.org/api/backdrop/core%21includes%21database%21database.inc/group/database/1.