Exceptions

Nette Database uses a hierarchy of exceptions. The base class is Nette\Database\DriverException, which extends PDOException and provides enhanced functionality for working with database errors:

  • The getDriverCode() method returns the error code from the database driver.
  • The getSqlState() method returns the SQLSTATE code.
  • You can use the getQueryString() and getParameters() methods to retrieve the original query and its parameters.

The DriverException class is extended by the following specialized exceptions:

  • ConnectionException – indicates a failure to connect to the database server.
  • ConstraintViolationException – the base class for database constraint violations, from which the following exceptions inherit:
    • ForeignKeyConstraintViolationException – violation of a foreign key constraint.
    • NotNullConstraintViolationException – violation of a NOT NULL constraint.
    • UniqueConstraintViolationException – violation of a uniqueness constraint.

The following example demonstrates how to catch a UniqueConstraintViolationException, which happens when trying to insert a user with an email that already exists in the database (assuming the email column has a unique index):

try {
	$database->query('INSERT INTO users', [
		'email' => 'john@example.com',
		'name' => 'John Doe',
		'password' => $hashedPassword,
	]);
} catch (Nette\Database\UniqueConstraintViolationException $e) {
	echo 'A user with this email already exists.';

} catch (Nette\Database\DriverException $e) {
	echo 'An error occurred during registration: ' . $e->getMessage();
}
version: 4.0 3.x