使用die()返回数组?



假设以下代码…

function helper_function($arg){
if($arg === NULL){
// I want this to act like die();
return ["error" => "the variable is null"];
}else{
return ["success!" => $arg];
}
}
// now, we use our helper function
$another_value = "test";
function my_function($another_value){
helper_function(NULL);
helper_function($another_value);
}

现在的问题是,我使用helper_function大约10+次在我的代码,所以我不能只是检查,如果一个错误存在

TLDR:my_function()应该返回错误。

如果不清楚,请让我知道。非常感谢

我不完全确定我正确理解你想要什么,但根据你提供的评论,我认为你正在寻找这样的东西:

function helper_function($arg){
if($arg === NULL) throw new Exception('the variable is null');
else{
return ["success!" => $arg];
}
}
function my_function($another_value) {
helper_function($another_value); // first call
helper_function(null); // second call
helper_function($another_value); // third call
}
try {
my_function('test');
} catch (Exception $e) {
/** one of the helper functions encountered an error do something to recover from this error **/
}

如果helper_function抛出异常,您也可以在外部函数中捕获该异常,因此您不必在每个helper_function之后检查错误。这样,如果my_function遇到错误,它将在代码的catch块中报告给您。

您可以在这里阅读更多关于Exceptions的信息:https://www.php.net/manual/en/language.exceptions.php

如果helper_function可以引发不同类型的错误,并且您想知道引发的确切错误,您可以通过以下方式修改函数:

function helper_function($arg) {
if ($arg === NULL) throw new Exception('null value received', 100);
else if ($arg === false) throw new Exception('false value received', 200);
else return ["success!" => $arg];
}
try {
my_function($another_value);
} catch (Exception $e) {
if ($e->getCode() === 100) {
// a null value was received somewhere, do something about it
} else if ($e->getMessage() === 'false value received') {
// a false value was received somewhere, do something about it
}
}

基本上,您可以从捕获的异常中检索异常消息和/或代码,因此可以引发不同类型的错误,并以您认为合适的方式处理这些错误。

最新更新