我有一个需要多次检查的函数,为此,我添加了多个函数,但是当某些内部函数失败时,它需要返回失败的响应,但并不需要并继续下一个内部函数
public static function doMultipleWorks(){
self::checkFirstCondition();
self::checkSecondCondition();
...
...
return response(['status' => true, 'data' => [...]]);
}
public static function checkFirstCondition(){
....
....
if(this != that){
return response(['status' => false, 'error_msg' => 'this is not equal to that']]
}
}
public static function checkSecondCondition(){
....
....
if(this != that){
return response(['status' => false, 'error_msg' => 'this is not equal to that']]
}
}
问题在于,如果第一个或第二个功能失败,它仍会继续并且不会脱离该功能。任何帮助将不胜感激。
答案 0 :(得分:0)
您不是要检查checkFirst
和checkSecond
的返回值,而是执行此操作或引发异常,而是要中断函数和try/catch
的异常
public function foo() {
if ($bar = $this->bar()) return $bar;
}
public function bar() {
if (something) return resp;
}
public function foo() {
try {
$this->bar();
}catch(\Exception $e) {
return [ 'success' => false, 'status' => $e->getMessage(), ];
}
}
public function bar() {
if (something) throw new Exception('Fail');
}
答案 1 :(得分:0)
您需要检查功能的响应并基于响应基础,您应该继续或中断进一步的过程。我相信您应该这样做:
public static function doMultipleWorks(){
$firstResponse = self::checkFirstCondition();
if ($firstResponse['status'] == false) {
return $firstResponse;
}
$secondResponse = self::checkSecondCondition();
if ($secondResponse['status'] == false) {
return $secondResponse;
}
...
...
return response(['status' => true, 'data' => [...]]);
}
public static function checkFirstCondition(){
....
....
if(this != that){
return response(['status' => false, 'error_msg' => 'this is not equal to that']]
}
}
public static function checkSecondCondition(){
....
....
if(this != that){
return response(['status' => false, 'error_msg' => 'this is not equal to that']]
}
}
希望它可以帮助您解决问题。