sandromiguel/php-throw

PHP 包,轻松抛出自定义异常。

v1.1.0 2024-03-30 16:46 UTC

README

PhpThrow (Beta) 是一个用于轻松抛出自定义异常的 PHP 包。

特性

  • 提供具有附加功能的自定义异常类。
  • 易于使用,可轻松集成到现有项目中。

安装

您可以通过 Composer 安装 PhpThrow

composer require sandromiguel/php-throw

使用方法

比较原生和 PhpThrow 异常

以下代码演示了如何使用原生 InvalidArgumentException 类和 ThrowInvalidArgumentException 类在提供的值小于零时抛出异常

原生 InvalidArgumentException

try {
    $value = -5;

    if ($value < 0) {
        throw new InvalidArgumentException('The value must be greater than or equal to 0.');
    }

    // ...
} catch (InvalidArgumentException $e) {
    echo $e->getMessage();
}

ThrowInvalidArgumentException:

try {
    $value = -5;

    ThrowInvalidArgumentException::ifZeroOrNegative($value);

    // ...
} catch (ThrowInvalidArgumentException $e) {
    echo $e->getMessage();
}

ThrowInvalidArgumentException

ThrowInvalidArgumentException 扩展了内置的 InvalidArgumentException,并提供了抛出与无效参数相关的异常的辅助方法。

create()

create($message):创建具有给定消息的新异常实例。

$email = 'not-a-valid-email-address';

try {
    // Validate the email address
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        throw ThrowInvalidArgumentException::create('Invalid email address');
    }

    // ...
} catch (ThrowInvalidArgumentException $e) {
    echo $e->getMessage(); // Output: Invalid email address
}

ifZeroOrNegative()

ifZeroOrNegative($value, $message = null):如果数值小于 0,则抛出异常。

try {
    ThrowInvalidArgumentException::ifZeroOrNegative(-1);
} catch (\PhpThrow\ThrowInvalidArgumentException $e) {
    echo $e->getMessage(); // Output: The value must be greater than or equal to 0.
}

ifZeroOrNegativeWithValue()

ifZeroOrNegativeWithValue($value, $message = null):如果数值为负,则抛出异常,包括错误消息中的值。

try {
    ThrowInvalidArgumentException::ifZeroOrNegativeWithValue(-1);
} catch (\PhpThrow\ThrowInvalidArgumentException $e) {
    echo $e->getMessage(); // Output: The value -1 must be greater than or equal to 0.
}

您还可以使用不带占位符的自定义消息

ThrowInvalidArgumentException::ifZeroOrNegativeWithValue(
    -1,
    'Value must be positive'
); // Output: Value must be positive. Provided -1

ThrowPageNotFoundException

ThrowPageNotFoundException 用于处理找不到页面时的异常。

示例:ThrowPageNotFoundException::forPage

use PhpThrow\ThrowPageNotFoundException;

$page = 'non-existent-page';
ThrowPageNotFoundException::forPage($page); // Throws an exception with the message "The page 'non-existent-page' was not found."

注意:默认情况下,错误代码设置为 404。您可以使用 code 参数进行更改。

贡献

想要贡献吗?所有贡献都欢迎。请参阅贡献指南

问题

如果您有问题,请通过 @sandro_m_m创建问题 联系我。

变更日志

请参阅 CHANGELOG.md

许可

本项目采用 MIT 许可证 - 请参阅 LICENSE 文件获取详细信息

待办事项

  • 实现额外的异常类和方法,以用于常见的验证

**~ 分享就是关爱 ~**