0
votes

I have a Yii2 application created using Basic Application Template. In web.php I require a file called params.php is present. To manage that, I use file exists function:

if(file_exists(__DIR__ . '/params.php')) {
        $params = require __DIR__ . '/params.php';
    } 

I would like to throw an Exception so I can show Yii error / debug page. I have tried:

if(file_exists(__DIR__ . '/params.php')) {
        $params = require __DIR__ . '/params.php';
    } else {
        throw new Exception("Error", 1000);
    }

But Yii2 Error handler does not catch it, I am not sure if at this point is already available. Is there another way to show it on any of those pages?

1
if your file is missing it should throw a fatal error do you mean that the application stil works if there is no file present ? - Muhammad Omer Aslam
@MuhammadOmerAslam I want to show a more user friendly error if possible. Right now I just show a blank page with the message. - Eduardo

1 Answers

2
votes

Error handler is registered on app initialization. Config from web.php is loaded before app initialization (since you need to get config first to initialize app), so error handler is not ready at this point.

You may postpone loading params by using events:

return [
    'on beforeRequest' => function () {
        if (file_exists(__DIR__ . '/params.php')) {
            Yii::$app->params = require __DIR__ . '/params.php';
        } else {
            throw new Exception('Error', 1000);
        }
    }
    // rest of app config
];