https://gist.github.com/esdras-schonevald/71a6730e6191c5e9c053e2f65b839eec
<?php
declare(strict_types=1);
/**
* 这是一个示例
* 如何使用枚举来创建自定义异常情况
* PHP 8.1^
*/
enum MyExceptionCase {
case InvalidMethod;
case InvalidProperty;
case Timeout;
}
class MyException extends Exception {
function __construct(private MyExceptionCase $case){
match($case){
MyExceptionCase::InvalidMethod => parent::__construct("Bad Request - Invalid Method", 400),
MyExceptionCase::InvalidProperty => parent::__construct("Bad Request - Invalid Property", 400),
MyExceptionCase::Timeout => parent::__construct("Bad Request - Timeout", 400)
};
}
}
// 测试我的自定义异常类
try {
throw new MyException(MyExceptionCase::InvalidMethod);
} catch (MyException $myE) {
echo $myE->getMessage(); // Bad Request - Invalid Method
}