phrity util errorhandler
v1.1.1
PHP錯誤處理可能有些頭痛。通常,應用程序使用系統級別錯誤處理程序和/或使用@前綴抑制錯誤。但是,當您的代碼需要在觸發錯誤上採取行動時,那些情況更加棘手。
該庫提供了兩種便利方法來處理代碼塊上的錯誤,要么通過拋棄異常或在發生錯誤時運行回調代碼。
當前版本支持PHP ^7.2|^8.0 。
與作曲家安裝;
composer require phrity/util-errorhandler
該課程提供了兩種主要方法; with()和withAll() 。不同之處在於, with()將立即採取錯誤並流產進一步的代碼執行,而withAll()將嘗試執行整個代碼塊,然後再對發生的錯誤作用。
use Phrity Util ErrorHandler ;
$ handler = new ErrorHandler ();
$ result = $ handler -> with ( function () {
// Code to execute
return $ success_result ;
});
$ result = $ handler -> withAll ( function () {
// Code to execute
return $ success_result ;
});上面的示例將運行回調代碼,但是如果發生錯誤,它將引發錯誤。錯誤消息和嚴重性將是觸發錯誤。
with()會在發生時立即投擲withAll()投擲;如果發生多個錯誤,第一個將被拋棄 use Phrity Util ErrorHandler ;
$ handler = new ErrorHandler ();
$ result = $ handler -> with ( function () {
// Code to execute
return $ success_result ;
}, new RuntimeException ( ' A specified error ' ));
$ result = $ handler -> withAll ( function () {
// Code to execute
return $ success_result ;
}, new RuntimeException ( ' A specified error ' ));上面的示例將運行回調代碼,但是如果發生錯誤,它將投擲可投擲。可拋出的可拋出式將帶有一個錯誤的$previous 。
with()會在發生時立即投擲withAll()投擲;如果發生多個錯誤,第一個將被拋棄 use Phrity Util ErrorHandler ;
$ handler = new ErrorHandler ();
$ result = $ handler -> with ( function () {
// Code to execute
return $ success_result ;
}, function ( ErrorException $ error ) {
// Code to handle error
return $ error_result ;
});
$ result = $ handler -> withAll ( function () {
// Code to execute
return $ success_result ;
}, function ( array $ errors , $ success_result ) {
// Code to handle errors
return $ error_result ;
});上面的示例將運行回調代碼,但是如果發生錯誤,它也會調用錯誤回調。
with()將在發生錯誤時立即運行錯誤回調;錯誤回調期望一個錯誤的實例withAll()將在代碼完成後運行錯誤回調;錯誤回調期望有一系列錯誤的感受和代碼回調的返回結果with()和withAll()都接受錯誤級別作為最後一個參數。
use Phrity Util ErrorHandler ;
$ handler = new ErrorHandler ();
$ result = $ handler -> with ( function () {
// Code to execute
return $ success_result ;
}, null , E_USER_ERROR );
$ result = $ handler -> withAll ( function () {
// Code to execute
return $ success_result ;
}, null , E_USER_ERROR & E_USER_WARNING ); SET_ERROR_HANDLER接受的值的任何值或組合都是可用的。默認值為E_ALL 。常數列表。
該類還具有全局set()和restore()方法。
use Phrity Util ErrorHandler ;
$ handler = new ErrorHandler ();
$ handler -> set (); // Throws ErrorException on error
$ handler -> set ( new RuntimeException ( ' A specified error ' )); // Throws provided Throwable on error
$ handler -> set ( function ( ErrorException $ error ) {
// Code to handle errors
return $ error_result ;
}); // Runs callback on error
$ handler -> restore (); // Restores error handler Phrity Util ErrorHandler {
/* Methods */
public __construct()
public with (callable $ callback , mixed $ handling = null , int $ levels = E_ALL ) : mixed
public withAll (callable $ callback , mixed $ handling = null , int $ levels = E_ALL ) : mixed
public set ( $ handling = null , int $ levels = E_ALL ) : mixed
public restore () : bool
}| 版本 | php | |
|---|---|---|
1.1 | ^7.4|^8.0 | 一些改進 |
1.0 | ^7.2|^8.0 | 初始版本 |