nhance/app/Helpers/exception_helper.php

36 lines
1.3 KiB
PHP

<?php
// app/Helpers/ExceptionHelper.php
if (!function_exists('handle_exception')) {
function handle_exception(Throwable $e, $logger = null, $response = null)
{
$code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500;
$isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException
|| $e instanceof \mysqli_sql_exception
|| $e instanceof \PDOException;
$context = [
'title' => get_class($e),
'type' => get_class($e),
'code' => $code,
'message' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine()
];
if ($logger) {
$logger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0);
} else {
log_message('error', "Exception: {$context['message']} in {$context['file']} on line {$context['line']}");
}
return $response->setJSON([
'status' => 'error',
'message' => $isDbError ? 'Data Access Error' : $e->getMessage(),
'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine()
])->setStatusCode($code);
}
}