我想知道在 RestAPI 中实现错误的方法是什么,实际上如果我的类中的方法产生异常我会返回这个 ...
if(mysqli_connect_errno()) {
throw new Exception("Can't connect to db.");
}
...但这是一种不好的做法,因为 API 应该返回一个 json。
所以我的想法是创建一个名为 Errors
的类,并且在每个类中,当错误被触发时,我只需调用相对错误编号来显示 json 错误。
有人有其他想法吗?
最佳答案
也许是这样的:
<?php
try {
// Do your stuff
if(mysqli_connect_errno()) {
throw new Exception("Can't connect to db.");
}
} catch (Exception $e) {
echo json_encode(array("success" => false, "message" => $e->getMessage()));
return;
}
关于php - 如何在 Rest API 中实现错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35433051/