首页 > 解决方案 > 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}}

但是我还需要指定错误代码(第一个参数),这对我的前端实现没有任何好处。除了语法,我对性能、安全性和面向未来的因素的差异感到好奇。

那么,除了个人偏好之外,还有什么理由更喜欢其中一个呢?

标签: phpwordpresserror-handlingwordpress-rest-apiwp-api

解决方案


我这样做:

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)

推荐阅读