我正在使用第三方xmlrpc API
。错误可以作为字符串或数组返回。我需要处理和格式化这些错误以使用户友好。 API不使用错误代码/字符串。
我目前正在使用switch-case
,但希望有所改进。
现有代码:
switch ($result) { // removed some blocks for sake of post
case 'Error:malformed_mac':
$result = $_POST['params'][0] . " is malformed. Please check you have entered it correctly.";
break;
case 'Error:no_such_mac':
$result = "Sorry, " . $_POST['params'][0] . " hasn't been registered.";
break;
}
无论如何,我可以将所有可能的错误的数组声明为键,并将自定义消息声明为值:
$errors = ['Error:no_such_mac' => 'custom error message1', 'Error:malformed_mac' => 'custom error message2'];
那该键是否在响应中打印出相应的值?还是我可以实现这一目标的另一种方法?
任何帮助表示赞赏。谢谢。
最佳答案
解决了以下问题:
$errors = [ "Error:no_such_mac" => "Mac address doesn't exist", "Error:malformed_mac" => "Mac address is malformed" ];
$word = "Error:no_such_mac";
echo strtr($word,$arr);
输出:
Mac address doesn't exist.
如果有更好的解决方案,请发布,我将标记为已接受答案。
关于php - 处理来自第三方API的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50988343/