【问题标题】:php how do I set different types of throw errorsphp如何设置不同类型的抛出错误
【发布时间】:2020-11-18 06:18:05
【问题描述】:

在 JavaScript 中,如果函数的参数是无效类型,这就是我创建抛出错误的方式。

function myFunction(num)
    if (typeof(num) !== 'number') {
        throw TypeError('num cannot be' + num);
    }
}

我如何在 PHP 上做到这一点?我知道有一个 throw 命令,但你如何设置错误类型。在上面的 JavaScript 示例中我将其设置为 TypeError,如何设置 PHP 抛出错误的错误类型以及 PHP 中的错误类型是什么?

function myFunction($num)
    if (gettype($num) !== 'boolean') {
        throw new Exception('$num cannot be ' , $num);;
    }
}

【问题讨论】:

标签: php function throw


【解决方案1】:

您可以尝试创建自定义异常示例

  final class CustomException extends \DomainException
{
    
    public function __construct()
    {
        $this->message = 'My Custom Message';
        $this->code = 400;
    }
}

并使用:

throw new CustomException();

或使用通用异常

throw new \Exception('message', 400);

异常有getMessage()和getCode()方法

【讨论】:

    【解决方案2】:

    PHP 具有与 JavaScript 非常相似的异常类。

    function myFunction($num)
        if (!is_bool($num)) {
            throw new InvalidArgumentException('$num cannot be ' . $num);;
        }
    }
    

    【讨论】:

    • InvalidArgumentException 将声明争论不是数字。有没有办法让布尔、字符串、数组等出现争论错误?
    • 你可以在消息中放任何你想要的东西。
    猜你喜欢
    • 2022-10-18
    • 2018-11-10
    • 1970-01-01
    • 1970-01-01
    • 2016-01-07
    • 2015-05-03
    • 2012-08-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多