I
I
Ivanoff-i2016-07-08 13:02:29
Yii
Ivanoff-i, 2016-07-08 13:02:29

How to make separate decoration of 404 and other errors for Yii2 module?

The project has created an api module that assumes the rest architecture. I would like that when clicking on the link ` http://site.ru/api/any character set` 404, and indeed any errors were shown in json format. And when you go to ` http://site.ru/not api` - in normal html. I guess urlManager must be involved somehow. How to do this without crutches? I have so far registered in urlManager at the very end after all the rules

[
    'api/<all:\w+>' => 'api/default/error',
    'api/<module>/<all:\w+>' => 'api/default/error',
]

So it seems to work, but maybe there is a more beautiful way?
Update
Solved in the following way. Registered in the bootstrap module:
if (preg_match('/^\/api\//', Yii::$app->request->url) !== 0) {
    Yii::$app->response->format = Response::FORMAT_JSON;

    Yii::$app->response->on(Response::EVENT_BEFORE_SEND, function($event) {
        /** @var Response $response */
        $response = $event->sender;
        if (isset($response->data['type']) && $response->statusCode !== 200) {
            unset($response->data['type']);
        }
    });
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim Fedorov, 2016-07-08
@qonand

If you have two API and non-API modules, you can simply set the desired server response format in each of the modules

M
Maxim Timofeev, 2016-07-08
@webinar

Read www.yiiframework.com/doc-2.0/guide-runtime-handlin...
Specifically Customizing Error Response Format
There is exactly an example with json

M
matperez, 2016-07-08
@matperez

For the API module, globally set \Yii::$app->response->format = Response::FORMAT_JSON; all data, including errors, will be returned as pure json.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question