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 | 初始版本 |