Refactor error handling and logging in API responses
This commit is contained in:
36
db_init.php
36
db_init.php
@ -283,3 +283,39 @@ function qdb_discard(string $tmpDb, $lockFp): void {
|
||||
@fclose($lockFp);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a read-only DB connection; on failure logs and returns a JSON error response.
|
||||
*
|
||||
* @return array{0: PDO, 1: string, 2: resource|null}|null
|
||||
*/
|
||||
function qdb_open_read_or_fail(): ?array {
|
||||
try {
|
||||
return qdb_open(false);
|
||||
} catch (Throwable $e) {
|
||||
if (function_exists('qdb_api_log_note_exception')) {
|
||||
qdb_api_log_note_exception($e);
|
||||
}
|
||||
require_once __DIR__ . '/lib/errors.php';
|
||||
error_log('qdb_open_read: ' . $e->getMessage());
|
||||
json_error('SERVER_ERROR', qdb_public_error_message($e, 'Database read'), 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a writable DB connection; on failure logs and returns a JSON error response.
|
||||
*
|
||||
* @return array{0: PDO, 1: string, 2: resource|null}|null
|
||||
*/
|
||||
function qdb_open_write_or_fail(): ?array {
|
||||
try {
|
||||
return qdb_open(true);
|
||||
} catch (Throwable $e) {
|
||||
if (function_exists('qdb_api_log_note_exception')) {
|
||||
qdb_api_log_note_exception($e);
|
||||
}
|
||||
require_once __DIR__ . '/lib/errors.php';
|
||||
error_log('qdb_open_write: ' . $e->getMessage());
|
||||
json_error('SERVER_ERROR', qdb_public_error_message($e, 'Database write'), 500);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user