0

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.

1 Answer 1

2

If you are using yii\rest\ActiveController, you could simply use a custom findModel method (no need to modify response as you did).

In your controller :

public function actions()
{
    $actions = parent::actions();

    // customize findModel
    $actions['view']['findModel'] = [$this, 'findModel'];

    return $actions;
}

public function findModel($id)
{
    $model = User::findOne($id);

    if (isset($model )) {
        return $model ;
    } else {
        throw new NotFoundHttpException("No user found");
    }
}

EDIT :

users/sdafsda is not handled by your user controller, you should fix your url rule : users/<id> instead of users/<id:\d+>.

Sign up to request clarification or add additional context in comments.

2 Comments

even findModel is not calling when we pass string. users/sdafsda.
Just one more question. What if I have two URLs ` 'users/<userEmail:[A-Za-z0-9 -_.]+>' => 'users/user-by-email',` AND ` 'users/<id>' => 'users/',` Where first one is for searching by email.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.