异常与状态
Coddy 面向 Go 开发者的 PHP 课程的第 25 课,共 48 课。
Go 通常会在成功结果旁边返回错误;panic 和 recover 是不同于常规验证的机制。PHP 使用异常和 catch 来处理契约失败。在修改状态前先验证,并明确转换预期的拒绝情况,这样即使操作失败,同一状态不变量也能保持。
抛出异常以表示契约失败,并且只在能够处理异常的边界捕获预期类别。在修改状态前验证所有前置条件,这样被拒绝的操作不会改变状态。finally 会在正常返回和异常传播期间运行。不要把所有 Throwable 都转换成成功,也不要隐藏编程错误。
Go 程序
package main
import ("fmt")
func setPositive(value *int,next int)error{if next<0{return fmt.Errorf("negative")};*value=next;return nil}
func main(){
value:=4;err:=setPositive(&value,-1);if err!=nil{fmt.Printf("rejected:%d\n",value)}
}
源程序输出:
rejected:4PHP 程序
demo.php
<?php
declare(strict_types=1);
try {throw new RuntimeException("bad");} catch(RuntimeException $e){echo "caught";} finally{echo ":done\n";}
PHP 输出:
caught:done挑战
简单输入为 [balance,amount]。只有当 amount 为正数且余额足够时,debit 才会修改被引用的余额。amount 非正数时抛出 InvalidArgumentException,资金不足时抛出 DomainException。驱动程序会捕获这两种异常,并输出 error:balance;成功时输出 ok:balance。余额初始值为非负数。
提供的 main 脚本会从标准输入读取一个 JSON 值,检查指定的公共 API,并输出结果。实现模块声明时不要输出内容;不要替换启动脚本,也不要从模块读取输入。输入符合指定的类型和范围。
编辑 Functions.php。main.php 是锁定的入口文件。依赖项使用带相对文件名的 require_once __DIR__。
亲手试试
<?php
declare(strict_types=1);
require_once __DIR__."/Functions.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}
function debitReport(array $input):string{$balance=$input[0];try{debit($balance,$input[1]);$status="ok";}catch(InvalidArgumentException|DomainException $e){$status="error";}return $status.":".$balance;}
$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
$b=7;try{debit($b,8);throw new RuntimeException("missing rejection");}catch(DomainException $e){}ensure($b===7,"atomic error");debit($b,2);ensure($b===5,"debit");
echo debitReport($input),"\n";
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Go 开发者的 PHP中的所有课
自己练习: PHP 在线编译器