I am working on Yii2 REST API and all APIs are working fine. I just want to know how can I modify 404 error message according to the controller and their actions.
For example.
I call api /users/100 and the response, when there is no user with 100 id, is
{
"name": "Not Found",
"message": "Object not found: 55554",
"code": 0,
"status": 404,
"type": "yiiwebNotFoundHttpException"
}
I have modified this response by the following code in web.php
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => false,
'showScriptName' => false,
'rules' => [
'<alias:index|about|contact|login|doc>' => 'site/<alias>',
'users/<id:\d+>' => 'users/',
]
]
'response' => [
'class' => 'yii\web\Response',
'on beforeSend' => function ($event) {
$response = $event->sender;
if ($response->data !== null && Yii::$app->request->get('suppress_response_code')) {
$response->data = [
'success' => $response->isSuccessful,
'data' => $response->data,
];
$response->statusCode = 200;
} else if ($response->statusCode == 404) {
$response->data = [
'success' => false,
'message' => 'Resource not found.',
];
$response->statusText = json_encode(['success' => false, 'message' => 'Resource not found.']);
} else if ($response->statusCode == 401) {
$response->statusText = json_encode(['success' => false, 'message' => 'Unauthorized: Access is denied due to invalid key.']);
}
},
'formatters' => [
\yii\web\Response::FORMAT_JSON => [
'class' => 'yii\web\JsonResponseFormatter',
'prettyPrint' => YII_DEBUG, // use "pretty" output in debug mode
'encodeOptions' => JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE,
// ...
],
],
],
But now this is the common message for all 404 errors.
What I want is, If it is for user then the message should be
No user found
if it is for categories
No categories found
All these APIs are following the default YII2 REST API standards.