php - 处理来自第三方API的错误

标签 php error-handling

我正在使用第三方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/

相关文章:

php - 在 MySQL 中设置名称 utf8?

php - 带有子菜单的菜单

matlab - Matlab 中的持久性错误对话框

javascript - 类型错误:showToastrMessage.init 不是函数

c++ - 如何捕捉这个错误? [C++]

c - 分离 fscanf 错误检查以便我可以传递特定消息?

php - 在 PHP 中更改来自 MySQL 的项目的顺序

php - 从 iPhone 应用程序将图像上传到服务器 PHP 脚本

php - DomDocument 和特殊字符

c# - C#获取ClassName : Exception TargetSite.DeclaringType.Name Vs MethodBase.GetCurrentMethod().DeclaryingType