Skip to content

Core\Ldap\LdapError

The error a directory operation throws when it fails.

Every method of a directory connection throws Core\Ldap\LdapError when the operation does not succeed. A login is rejected, an entry does not exist, the account has no permission, or the server does not answer. The error has three properties. kind is a Core\Ldap\LdapError::Kind case that says why the operation failed. code is the number the server sent, or null when the server sent no answer. message is a sentence for your log.

LdapError is a RuntimeError, so a catch (RuntimeError $error) block also catches it.

Good to know: the message never contains a password. A wrong password and a user that does not exist give the same kind and the same message.

Examples

The examples below run with this configuration file.

nvs.toml
# These examples use the LDAP directory server on this computer at port 16636.
# `tls_ca_file` is the certificate that the server's certificate is checked against.
[ldap.corp]
url = "ldaps://127.0.0.1:16636"
base = "DC=example,DC=test"
user = "CN=Reader,OU=Company,DC=example,DC=test"
password = "Novis-reader-1"
tls_ca_file = "../../../../tests/db/ca.crt"
timeout = "5s"
# The program may open the `corp` directory.
[capabilities.ldap]
connect = ["corp"]

A search under a unit that does not exist

<?nvs
// Shows what a `Core\Ldap\LdapError` contains when the directory rejects a search.
// requires: samba-ad
var $corp = Core\Ldap::connect('corp');
var $people = Core\Ldap\Filter::equals('objectClass', 'user');
try {
// This unit does not exist, so the search throws an error.
foreach ($corp->search($people, { base: 'OU=Nowhere,DC=example,DC=test' }) as Core\Ldap\Entry $person) {
echo $person->string('cn') ?? '', "\n";
}
} catch (Core\Ldap\LdapError $error) {
// `kind` says why the operation failed. This prints `NoSuchObject`.
echo $error->kind == Core\Ldap\LdapError::Kind::NoSuchObject ? 'NoSuchObject' : 'another reason', "\n";
// `code` is the number the server sent. This prints `32`.
echo $error->code ?? 'no code', "\n";
}
// `LdapError` is a `RuntimeError`, so a `catch (RuntimeError ...)` block also catches it.
try {
$corp->delete('CN=Nobody,OU=Nowhere,DC=example,DC=test');
} catch (RuntimeError $failure) {
// This prints `caught: yes`.
echo 'caught: ', $failure is Core\Ldap\LdapError ? 'yes' : 'no', "\n";
}
Output
NoSuchObject
32
caught: yes