How to catch a thrown exception and implement some rendering logic

Hi there,

I’m building an application divided in two parts

  • a rest-api which communicates with an iOS app
  • a dashboard with some administration tasks

My rest-api controllers are stored in a separated namespace controllers/api.

I’ve added an authentication behaviour to my ProjectController:

/**
 * Add specific behavior to the controller.
 *
 * @return array
 */
public function behaviors() {
    $behaviors = parent::behaviors();

    /* Attach authenticator for access-token login */
    $behaviors['authenticator'] = [
        'class' => QueryParamAuth::class,
    ];

    return $behaviors;
}

Furthermore, there’s an action where I can request a product:

    /**
     * This method checks a given project number and
     * returns additional information serialized in a json object.
     *
     * @throws \yii\base\ExitException
     */
    public function actionRequest() {
        $params = Yii::$app->request;
        $projectId = (int)$params->get('project-id');

        /*
         * If no project could be found for the given project id return
         * an error message in the jsend-styled json-response.
         */
        if(!$projectId || $projectId !== 2) {
            $this->renderJSON(null, 'fail', 'no products could be found.');
        }

        /* project could be found, return success */
        $this->renderJSON(['project-id' => $projectId, 'title' => 'Testprojekt']);
    }

That works perfectly but now I also would like to return json-responses if the login-process fails. When login failed, QueryParamAuth's authenticate method will be called and the exception UnauthorizedHttpException will be thrown in AuthMethod.

I would like to differentiate the response (json or ‘just’ normal) if the request calls an controller in api namespace (or not). I’ve looked for something like middlewars, but I couldn’t find anything. How can I implement my idea?

Thank you.

As far as I know, exceptions will be automatically converted to JSON or XML when using Yii rest module:
54%20PM

Are you having trouble with this?

1 Like

Hi, thank you. I just implemented the default Controller instead of yii\rest\ActiveController.

1 Like

Yii had the idea of middlewares long before other major php frameworks, read guide for filters

https://www.yiiframework.com/doc/guide/2.0/en/structure-filters