使用参数编号,函数名称自动抛出异常

时间:2013-02-12 14:16:26

标签: php

我抛出这样的例外:

public function findRole($role)
{
    if(!is_string($role)){
        throw new \InvalidArgumentException(
            sprintf('Role should be a string, %s given.', gettype($role))
        );
    //...
    }

我见过这样的例外情况,并希望这样做:

  

错误:json_decode()期望参数1为字符串,给定数组。

我有可能自动抛出这样的异常,以便异常自动输出函数的名称无效的参数号吗?

3 个答案:

答案 0 :(得分:1)

不是自动的,但你可以制作一种通用模板,例如:

if(!is_string($role)) {
    throw create_invalid_argument_exception(__METHOD__, 1, 'string', $role);
}



function create_invalid-argument_exception($method, $argNo, $expectedType, $actualValue) {
    return new \InvalidArgumentException(
        sprintf(
            '%s expects parameter %d to be %s, %s given.',
            $method, $argNo, $expectedType, gettype($actualValue)
        )
    );
}

答案 1 :(得分:1)

您想要的那些错误由PHP自动打印,并且可能使用set_error_handler函数很好地处理。你自己无法模拟相同的行为(可能没有无意义的黑客行为)。因此,您被迫以异常方式行事。

你应该注意一个例外:type hinting;只能用于数组,类,对象和可调用函数(函数):

public function acceptArray(array $array);
public function acceptObject(object $o);
public function acceptClass(MyClass $o);
public function acceptCallback(callable $f);

如果使用任何其他类型的变量调用这些函数,则会像您发布的特定错误一样抱怨。

我之前谈到的黑客可能包括自己重新定义每种类型:

class Int {...}
class String {...}
class Float {...}
class Bool {...}

然后像这样使用它:

$bool = new Bool(true);
acceptString($bool); // public function acceptString(String $s);

会触发错误。但这只是 PHP应该如何工作。所以我仍然建议你按照你最初的想法去做。

答案 2 :(得分:-1)

要捕获异常,您必须使用构造:

try{
    /** you code here  */
}catch(Exception $e){
    /** convert $e to json and output */
}

用它包装你的主要功能