Error support

Berkeley DB offers programmatic support for displaying error return values.

The db_strerror() function returns a pointer to the error message corresponding to any Berkeley DB error return, similar to the ANSI C strerror function, but is able to handle both system error returns and Berkeley DB specific return values.

For example:

  1. int ret;
  2. ...
  3. if ((ret = dbp->put(dbp, NULL, &key, &data, 0)) != 0) {
  4. fprintf(stderr, "put failed: %s\n", db_strerror(ret));
  5. return (1);
  6. }

There are also two additional error methods, DB->err() and DB->errx(). These methods work like the ANSI C X3.159-1989 (ANSI C) printf function, taking a printf-style format string and argument list, and writing a message constructed from the format string and arguments.

The DB->err() method appends the standard error string to the constructed message; the DB->errx() method does not. These methods provide simpler ways of displaying Berkeley DB error messages. For example, if your application tracks session IDs in a variable called session_id, it can include that information in its error messages:

Error messages can additionally be configured to always include a prefix (for example, the program name) using the DB->set_errpfx() method.

  1. #define DATABASE "access.db"
  2. int ret;
  3. (void)dbp->set_errpfx(dbp, program_name);
  4. if ((ret = dbp->open(dbp,
  5. NULL, DATABASE, NULL, DB_BTREE, DB_CREATE, 0664)) != 0) {
  6. dbp->err(dbp, ret, "%s", DATABASE);
  7. dbp->errx(dbp,
  8. "contact your system administrator: session ID was %d",
  9. session_id);
  10. return (1);
  11. }

For example, if the program were called my_app and the open call returned an EACCESS system error, the error messages shown would appear as follows:

  1. my_app: access.db: Permission denied.
  2. my_app: contact your system administrator: session ID was 14

Note

Equivalent methods exist for informational messages. See DB->msg() and DB->set_msgpfx() for details.