A
A
Alexey Voropaev2016-06-05 23:02:35
Yii
Alexey Voropaev, 2016-06-05 23:02:35

How to catch Exception correctly?

How to handle Exception so standard yii2 404 page appears?
Without creating your own class and so that processing is performed for all exceptions
a00e9b1bb0844b1797898641cbc67b6b.bmp

try
            {
                $activeCategory = NewsCategory::find()
                        ->where(['name_en' => Yii::$app->request->get('category')])
                        ->one();
                $model = News::find()
                        ->where(['newsCategory_id' => $activeCategory->id]);
            } catch (Exception $ex) {
                /* */
            }

I am sure that my problem is easily solved, but in Google I find only articles on creating my handler

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
polar-bear, 2016-06-06
@boomrap

Add a slash before Exception in your code. Then it will work as you need.

} catch (\Exception $ex) {
    throw new NotFoundHttpException('Not found');
}

A
Alexey Voropaev, 2016-06-06
@boomrap

Did as you said, nothing has changed
2a7af7a33f9b456b9f4b3385f3c17628.bmp

N
Nikita, 2016-06-06
@bitver

Take away try,

$activeCategory = NewsCategory::find()
                        ->where(['name_en' => Yii::$app->request->get('category')])
                        ->one();
if(!$activeCategory) { // Или ошибка
  throw new NotFoundException(); 
}
$id = $activeCategory->id; // Иначе всё ок

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question