PHP如何实现类die效果的辅助函数 遇错直接返回错误数组无需逐次校验
实现方案
这里提供两种可落地的实现方式:
方案1:使用异常冒泡机制(推荐)
直接修改辅助函数的错误返回逻辑为抛出自定义异常,异常会自动中断后续代码执行,向上冒泡到上层捕获逻辑,无需每次调用后手动判断返回值。
实现代码如下:
// 自定义业务异常类,用于区分辅助函数抛出的错误 class HelperFunctionError extends Exception {} function helper_function($arg){ if($arg === NULL){ // 出错时直接抛出异常,终止后续逻辑执行 throw new HelperFunctionError("the variable is null"); }else{ return ["success!" => $arg]; } } $another_value = "test"; function my_function($another_value){ try { // 无论调用多少次辅助函数,都不需要单独写判断逻辑 helper_function(NULL); helper_function($another_value); // 所有调用都成功后返回正常结果 return ["status" => "all operations succeeded"]; } catch (HelperFunctionError $e) { // 捕获到辅助函数抛出的错误后直接返回对应错误数组 return ["error" => $e->getMessage()]; } }
方案2:兼容原有辅助函数逻辑的封装方案
如果不方便修改原有helper_function的返回逻辑(比如其他业务代码仍依赖它返回错误数组),可以封装一层调用代理,在代理层完成返回值判断和异常抛出:
实现代码如下:
// 原有辅助函数保持不变 function helper_function($arg){ if($arg === NULL){ return ["error" => "the variable is null"]; }else{ return ["success!" => $arg]; } } // 封装调用代理层 function call_helper($arg) { $result = helper_function($arg); // 统一在代理层判断返回值,出错就抛异常 if (isset($result['error'])) { throw new Exception($result['error']); } return $result; } $another_value = "test"; function my_function($another_value){ try { // 后续调用都使用封装好的代理方法即可 call_helper(NULL); call_helper($another_value); return ["status" => "all operations succeeded"]; } catch (Exception $e) { return ["error" => $e->getMessage()]; } }
内容的提问来源于stack exchange,提问作者lolc
相关产品推荐
相关产品推荐

