A
A
Anton Artyomov2016-09-15 16:02:18
Yii
Anton Artyomov, 2016-09-15 16:02:18

How to catch a database error (Exception) in Yii2 Active Record?

Hello. Yii2 + Postgesql.
An ID field of type UUID.
I'm trying

try {
            $file = Files::find()->where(['CREATED_BY' => \Yii::$app->user->id, 'ID' => $id])->one();
        } catch (Exception $ex) {
            throw new \yii\web\NotFoundHttpException('Запись не найдена');
        }

For the test, I pass the string '234234' to $id. The corresponding database error is thrown to the browser about the mismatch of the passed value with the type of the field.
Why does try catch not catch the error? How to intercept it correctly? I couldn't google it either. Googled "Yii2 Active Record try catch" and combinations...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton, 2016-09-15
@ArtyomovAnton

Which Exception class are you using (give namespace)? Try using \yii\db\Exception or global \Exception in general.

M
Maxim Timofeev, 2016-09-15
@webinar

Because find() does not return an error, but returns null, so in this case, you need to check for null or not

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question