3 回答

TA貢獻1824條經驗 獲得超8個贊
記錄異常和通知它們是整個項目必須全局解決的兩個任務。它們不應該用幫助try-catch塊來解決,因為通常try-catch應該使用幫助塊來嘗試解決產生異常的具體本地定位問題(例如,修改數據或嘗試重復執行)或執行操作以恢復應用狀態。關于異常的日志記錄和通知是應該使用全局異常處理程序解決的任務。PHP 有一個本地機制來配置一個帶有set_exception_handler函數的異常處理程序。例如:
function handle_exception(Exception $exception)
{
//do something, for example, store an exception to log file
}
set_exception_handler('handle_exception');
配置處理程序后,所有拋出的異常都將使用handle_exception()函數進行處理。例如:
function handle_exception(Exception $exception)
{
echo $exception->getMessage();
}
set_exception_handler('handle_exception');
// some code
throw Exception('Some error was happened');
此外,您始終可以使用幫助restore_exception_handler函數禁用當前異常處理程序。
在您的情況下,您可以創建一個簡單的異常處理程序類,該類將包含日志記錄方法和通知方法,并實現一種機制來處理將選擇必要方法的異常。例如:
class ExceptionHandler
{
/**
* Store an exception into a log file
* @param Exception $exception the exception that'll be sent
*/
protected function storeToLog(Exception $exception)
{}
/**
* Send an exception to the email address
* @param Exception $exception the exception that'll be sent
*/
protected function sendToEmail(Exception $exception)
{}
/**
* Do some other actions with an exception
* @param Exception $exception the exception that'll be handled
*/
protected function doSomething(Exception $exception)
{}
/**
* Handle an exception
* @param Exception $exception the exception that'll be handled
*/
public function handle(Exception $exception)
{
try {
// try to store the exception to log file
$this->storeToLog($exception);
} catch (Exception $exception) {
try {
// if the exception wasn't stored to log file
// then try to send the exception via email
$this->sendToEmail($exception);
} catch (Exception $exception) {
// if the exception wasn't stored to log file
// and wasn't send via email
// then try to do something else
$this->doSomething($exception);
}
}
}
}
之后,您可以注冊此處理程序
$handler = new ExceptionHandler();
set_exception_handler([$handler, 'handle']);
$routes = require_once(__DIR__.'/Routes.php');
$router = new RouteFactory($routes, $request, \Skletter\View\ErrorPages::class);
$router->buildPaths('Skletter\Controller\\', 'Skletter\View\\');
$app = new Application($injector);
$app->run($request, $router);

TA貢獻1878條經驗 獲得超4個贊
如果我是你,我會在“kernel.exception”事件中捕獲該異常,原因很簡單:你的記錄器無處不在。只需編寫一個監聽器,測試類似的東西
if ($e instanceof MONOLOG_SPECIFIC_EXCEPTION) {
// handle exception here
}
如果您也使用命令,請對“console.exception”事件執行相同的操作。

TA貢獻1735條經驗 獲得超5個贊
您可以嘗試一些解決方案。
您可以將記錄器包裝在您自己的另一個類中,處理那里的所有異常和可能的錯誤,并使用您的類進行日志記錄。
有時無法捕獲所有錯誤,異常未得到處理并且發生極少數情況(即 IO 錯誤),您可以決定接受它。在這種情況下,您可以使用您自己提出的解決方案。使用 ELK 包,您將能夠根據您感興趣的參數配置手表監視器。
- 3 回答
- 0 關注
- 232 瀏覽
添加回答
舉報