php - WP_REST_Response 与 WP_Error
问题描述
我对如何在 Wordpress 的 REST API 中处理错误感到有些困惑。在他们的示例中,他们建议使用WP_Error
来返回错误,但WP_REST_Response
将 HTTP 状态代码作为第二个参数,这使得它更短,更符合我的口味。
所以我正在比较这种返回错误的方式:
return new WP_REST_Response(array('error' => 'Error message.'), 400);
有了这个:
return new WP_Error('rest_custom_error', 'Error message.', array('status' => 400));
使用第一个选项,我可以在我的回复中只包含错误文本,这对我来说已经足够了。所以响应看起来像这样:
{"error":"错误信息。"}
第二个更详细:
{"code":"rest_custom_error","message":"错误信息。","data":{"status":403}}
但是我还需要指定错误代码(第一个参数),这对我的前端实现没有任何好处。除了语法,我对性能、安全性和面向未来的因素的差异感到好奇。
那么,除了个人偏好之外,还有什么理由更喜欢其中一个呢?
解决方案
我这样做:
WP_REST_Response // Used when endpoint code runs just fine but needs to
// tell the client about some other downstream error (e.g. 4xx)
WP_Error // Used when endpoint code has an issue and needs to tell you
// it didn't compute or couldn't find resources etc (e.g. 5xx)
推荐阅读
- javascript - firebase Stripe API 在第一次付款过程中失败
- python - 如何将两个数据框逐列相乘?
- python - 使用 jupiter 对大型数据集进行 Panda 操作
- typescript - 如何在使用 reduxForm 包装的组件内使用 FormInstance 道具(提交)
- react-native - 可搜索的平面列表反应原生
- python - 在pygame中与敌人碰撞使玩家失去多条生命
- python-3.x - 在同一行写入输出,在 python 控制台上完全清除前一行
- python-3.x - 如何使用 python 将多个 CSV 文件导入 PostgreSQL 表?
- wordpress - 阻止对 Wordpress 视频的直接 URL 访问
- java - 我们如何使用Android代码获取根节点的子节点数?