Answer the question
In order to leave comments, you need to log in
How to handle exceptions in controller in Yii2?
I know that the question has already been raised many times. But no solutions have yet been found.
Let's take the standard controller from the example:
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
} else {
Yii::$app->session->setFlash('error', 'There was an error sending your message.');
}
return $this->refresh();
} else {
return $this->render('contact', [
'model' => $model,
]);
}
}
public function actionContact()
{
$model = new ContactForm();
try {
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
} else {
Yii::$app->session->setFlash('error', 'There was an error sending your message.');
}
}
} catch (UserException $e) {
Yii::$app->session->setFlash('error', $e->getMessage());
} catch (\Exeption $e) {
Yii::$app->session->setFlash('error', 'Something went wrong.');
}
return $this->render('contact', [
'model' => $model,
]);
}
Answer the question
In order to leave comments, you need to log in
The config specifies the error display page for exception
'components' => [
'errorHandler' => [
'errorAction' => 'site/error',
],
]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question