【发布时间】:2022-01-22 07:19:22
【问题描述】:
假设我有 2 个函数,我向 init 函数发送 ajax 请求并调用 check 函数的 init 函数
function init(Request $request){
$this->check($request);
}
function check(Request $request){
$request->validate(['something' => 'required']);
}
在这种情况下,如果验证失败,laravel 会使用 Status Code: 422 返回对 ajax 调用的响应,我不需要返回任何响应
现在,如果我想检查其他内容,如果失败,我想像验证失败响应一样响应
function cehck(Request $request){
if($somethign_else_failes)
{
return response()->json(['errors' => ['email' => ['The email is invalid.']]], 422);
}
}
但这不会返回 ajax 调用响应...它只会返回给init 函数
我需要在init 函数中添加另一个返回
基本上我不想在嵌套函数中有多个返回,如果它在任何级别失败,我想返回该级别的 ajax 响应
我愿意
function init(Request $Request){
$this->cehck();
// do the rest of code
}
function check(){
if($something_wrong)
//abort with reponse message
}
而不是这样的
function init(Request $Request){
$response = $this->cehck();
if( $response == failed )
{
//abort with reponse message
}
// do the rest of code
}
function check(){
if($something_wrong)
return failed flag ;
}
【问题讨论】:
-
那么你需要抛出一个异常......这就是调用堆栈的工作方式,你需要在展开堆栈时从它们返回东西,或者你可以抛出一个通过它们冒泡的异常... 为什么你不想从
init返回一个值?如果这些东西没有失败怎么办,您的操作是否根本没有返回任何响应? -
@lagbox 然后我必须检查父/调用者函数中子函数的响应......看看我是否必须中止或继续使用其余代码......我想要避免在我的代码中出现额外的
if并中止子函数中的操作 -
那么你唯一的选择就是抛出异常
-
return $this->check(...) -
@nice_dev 我需要检查父函数中子函数的响应,看看我是否必须中止或让其余代码执行......我想避免额外的@父函数中的 987654333@ ...我已在我的问题中添加了其他信息