Track and throw errors from the correct DB

Previously, even when an error occurred in an operation acting on the source
database, `bdb_handle_error(ctbdb)` was being called. This change tracks
whether an error occurs during operations on `sbdb` or `tbdb`, and raises an
exception using the correct database accordingly.