Handling InvalidRouteException

Current project (I’ve used Yii1 & 2 for several projects) is Angular IO in the front-end and Yii is mainly used to provide a REST API to Angular (plus some views that produce CSV or PDF downloads).
Some bots like to try and break in so they produce InvalidRouteException which goes into @runtime/logs/app
We monitor this log closely, as any PHP bug we put into our code will show up here. We like to fix bugs before the user reports them :slight_smile:
So I try to remove nuisance stuff from this log, keep it clean.
So I’m looking for a way to handle this exception and redirect to the application’s home page, preferably without modifying core Yii.

You can ignore exceptions. Here is a sample that you can adopt

[
        'traceLevel' => 3,
        'targets' => [
            [
                'class' => 'yii\log\EmailTarget',
                'mailer' => 'mailer',
                'levels' => ['error', 'warning'],
                'message' => [
                    'from' => [...],
                    'to' => [...],
                    'subject' => '...' . date('d-m-Y'),
                ],
                'except' => [
                    'yii\web\HttpException:404',
                    'yii\web\HttpException:401',
                    'yii\web\HttpException:403',
                ],
            ],
            [
                'class' => 'yii\log\FileTarget',
                'levels' => ['error', 'warning'],
                'except' => [
                    'yii\web\HttpException:404',
                ],
            ]
        ],
    ]
1 Like

Thanks for hint, I was focussed on handling the exception but your idea is much better.

So far no luck.
I’ve tried
'except' => ['InvalidRouteException']
and
‘except’ = [‘InvalidRouteException:*’]
and
‘except’=[‘InvalidRouteException:404’]

but I’m still seeing this in the logs:
2022-07-01 16:51:44 [58.96.71.93][-][-][error][yii\web\HttpException:404] yii\base\InvalidRouteException: Unable to resolve the request "abc/abc". in /home/lamp/skilodge/release/master/release20220701_1/vendor/yiisoft/yii2/base/Module.php:561

Sorry for late reply. I missed your reply.
You are missing the namespace. Compare mine to yours

[
    'class' => 'yii\log\FileTarget',
    'levels' => ['error', 'warning'],
    'except' => [
        'yii\web\HttpException:404',
        'yii\base\InvalidRouteException',
    ]
]

Thanks, I’ll try that. I should have looked more carefully!

2 Likes

Thanks for all the help, I found success with this code:

'except' => [
                'yii\base\InvalidRouteException',
                'yii\web\HttpException:404',
                'yii\web\NotFoundHttpException',
              ]