【问题标题】:Is there any way to return a custom error on permission_callback in WordPress REST API有什么方法可以在 WordPress REST API 中的权限回调上返回自定义错误
【发布时间】:2020-09-26 18:47:33
【问题描述】:

我已经用这个代码注册了路线

register_rest_route(
            "v1/senders",
            "read",
            [
                "methods"             => WP_REST_Server::READABLE,
                "callback"            => [
                    new Sender(),
                    "read"
                ],
                "permission_callback" => function ( WP_REST_Request $request ) {
                    return /* Function returning true/false */;
                }
            ]
        );

权限回调函数返回false时收到此消息:

{
    "code": "rest_forbidden",
    "message": "Sorry, you are not allowed to do that.",
        "data": {
        "status": 401
    }
}

是否有任何方法可以自定义此消息 - 挂钩、过滤器等?我在前端使用不同的数据格式来成功响应,所以我也需要修改这些响应。提前感谢您的回复!

【问题讨论】:

    标签: json wordpress-rest-api


    【解决方案1】:

    很容易实现:

    register_rest_route(
            "v1/senders",
            "read",
            [
                "methods"             => WP_REST_Server::READABLE,
                "callback"            => [
                    new Sender(),
                    "read"
                ],
                "permission_callback" => function ( $request ) {
                    //Function returning true/false/WP_Error;
                    if( YES ){ //-->your custom permission condition!
                        return true;
                    }else{
                        //Modify the below message and/or status code if you want!
                        return new WP_Error(
                            'rest_forbidden',
                            __( 'Sorry, you are not allowed to do that!!!.' ),
                            array( 'status' => rest_authorization_required_code() )
                        );
                    }
                }
            ]
        );
    

    【讨论】:

    • 结果将是相同的 JSON 对象,但我需要 WordPress 在出错时返回我自己的 JSON 对象结构。对不起,不清楚的问题。但是,老实说,您的回答是对我所问问题的准确回答,但不是我所期望的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-20
    • 2015-03-21
    • 2019-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多