【问题标题】:WP_REST_Response vs WP_ErrorWP_REST_Response 与 WP_Error
【发布时间】:2018-10-12 15:15:30
【问题描述】:

我对如何在 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 如何处理响应有关。只需使用第二个变体。

标签: php wordpress error-handling wordpress-rest-api wp-api


【解决方案1】:

我这样做:

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)

【讨论】:

    猜你喜欢
    • 2017-11-15
    • 2017-02-06
    • 2018-08-18
    • 1970-01-01
    • 2019-04-19
    • 1970-01-01
    • 1970-01-01
    • 2015-03-13
    • 1970-01-01
    相关资源
    最近更新 更多