transprime-research / attempt
对象式try-catch语句的流畅助手
2.0.0
2024-04-30 17:33 UTC
Requires
- php: >=7.4
- transprime-research/arrayed: ^2.2
Requires (Dev)
- phpunit/phpunit: ~8.0
- symfony/var-dumper: ^6.4
This package is auto-updated.
Last update: 2024-09-30 18:19:16 UTC
README
关于Attempt
用PHP面向对象的方式实现try和catch
像专业人士一样操作 🆗
使用方法
$response = attempt(fn() => $this->client->get('ninja')) ->catch(ConnectException::class) ->done(fn() => []); //done can be replaced with ()
安装
最低要求是PHP 7.2+和Composer。
使用以下命令安装
composer require transprime-research/attempt
其他使用方法
$response = Attempt::on(fn() => $this->client->get('ninja')) ->catch(AttemptTestException::class)(); // or ->done() // Do something with Response
catch
方法接受一个异常对象
$response = Attempt::on(fn() => $this->client->get('ninja')) ->catch(\AttemptTestException())(); // or ->done() // Do something with Response
设置默认响应
$response = Attempt::on(fn() => $this->client->get('ninja')) ->with(['abc']) ->catch(AttemptTestException::class) ->done(); // ['abc'] is returned if exception is caught
// with default value attempt(fn() => $this->execute()) ->catch(AttemptTestException::class, 'It is done') //returns 'It is done' ->done(); // closure as default value attempt(fn() => $this->execute()) ->catch(AttemptTestException::class, fn() => 'It is done') //returns 'It is done' ->done(); // handle the resolved default value in done() attempt(fn() => $this->execute()) ->catch(AttemptTestException::class, fn() => 'error') //returns 'It is done' ->done(fn(Exception $ex, $severity) => logger($severity, $ex));
多个异常
$response = Attempt::on(fn() => $this->client->get('ninja')) ->catch(AttemptTestException::class, HttpResponseException::class)() // Do something with Response
多个catch块
attempt(fn() => $this->execute()) ->catch(NinjaException::class, 'Ninja error') //returns 'It is done') ->catch(AnotherExeption::class, 'Another error') //returns 'It is done' ->done(fn($ex) => logger()->error($ex));
使用捕获的异常响应做更多操作
$response = Attempt::on(fn() => $this->client->get('ninja')) ->catch(AttemptTestException::class, HttpResponseException::class) ->done(fn(\HttpResponseException $e) => logger()->error($e->getMessage())); // Do something with Response
更多功能:将默认值的执行传递给可调用的类
// loading...
更多信息
本包是"The Code Dare"系列的一部分。
在此查看本系列的其他包
- https://github.com/transprime-research/piper [PHP中的智能管道]
- https://github.com/transprime-research/arrayed [更智能的数组,现在像对象一样使用]
- https://github.com/omitobi/conditional [智能PHP if...elseif...else语句]
- https://github.com/omitobi/carbonate [智能Carbon + Collection包]
- https://github.com/omitobi/laravel-habitue [具有集合响应的Jsonable Http Requester包]
类似包
- 待定
许可证
MIT (见LICENCE文件)