Answer the question
In order to leave comments, you need to log in
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',
]
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
If you have two API and non-API modules, you can simply set the desired server response format in each of the modules
Read www.yiiframework.com/doc-2.0/guide-runtime-handlin...
Specifically Customizing Error Response Format
There is exactly an example with json
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question