php - Yii2开发Restful API的时候如何为不同的Module显示各自的错误格式?
伊谢尔伦
伊谢尔伦 2017-04-11 09:40:12
0
4
383

框架:Yii2 Adv
目录结构如下

api/
    models/
    web/
    modules/
        v1/
            controllers/
            ...
        v2/
            controllers/
            ...
    config/
        main.php
        ...

现在打算针对v2版本的Api使用不同的错误显示格式, 所以我按照文档上说明的对response组件添加了on beforeSend事件, 但是实践中发现这样设置事件只能够对应用组件起作用, 对于Module的组件无法触发事件.
config/main.php代码如下:

return [
    'id' => 'app-api',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log',],
    'modules' => [
        'v1' => [
            'class' => 'api\modules\v1\Module',
            'basePath' => '@app/modules/v1',
            'components' => [
            ]
        ],
        'v2' => [
            'class' => 'api\modules\v2\Module',
            'basePath' => '@app/modules/v2',
            'components' => [
                'response' => [
                    'class' => \yii\web\Response::class,
                    'on beforeSend' => function ($event) {
                        /** @var \yii\web\Response $res */
                        $res = $event->sender;
                        if (!$res->isSuccessful) {
//                            do something here...
//                            ...
                        }
                    }
                ],
            ],
        ]
    ],
    ...

如果直接采用文档http://www.yiiframework.com/d...中的方法会同时对v1和v2两个模块起作用, 导致v1正在使用的接口与App不兼容.
如果只打算对单独的Module设置Response还有什么实现方式呢?

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(4)
黄舟

可以做到。

在每个模块的 Module.php 内的 Module::init() 方法中 给 Response::EVENT_BEFORE_SEND 绑定handler即可。

还需要在 Module.php 中绑定因 module 而异的 [errorHandler].

具体参考 module 和 event 文档

PHPzhong

Yii2应该是不支持的,如果要做到这个事情,可以考虑在error handler中去分析url是那个模块,当然这是比较挫的实现方式,如果楼主找到了更好的解决方案,欢迎分享

洪涛

错误显示格式指的是什么意思?不同的错误页面?

PHPzhong

我最后的解决办法:

1.在apimodulesv1Module.php里:

 public function init()
    {
        parent::init();

        // custom initialization code goes here
        $handler = new ApiErrorHandler();
        Yii::$app->set('errorHandler', $handler);
        $handler->register();
    }

2.在apimodulesv1components新建ApiErrorHandler.php文件

3.config/main.php添加:

'errorHandler' => [
            'class' => 'api\modules\v1\components\ApiErrorHandler',
            'errorAction' => 'site/error',
        ],   

4.在访问不存的路由后,自定义的error信息就出来了,类似这样:

{"meta":{"status":"error","errors":[{"message":"Not Found","code":404}]}}

替代了之前的:

An Error occurred while handling another error:
exception 'yii\base\InvalidRouteException' with message 'Unable to resolve the request "site/error".'  ...... 

有想详细了解的可以留言.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!