Skip to content
Advertisement

Laravel: How to configure eloqent to throw exception on database timeout?

If database is not available there is some seconds of loading. Then the log shows this error, should’nt that trigger the exception handler? (other errors end up their as expected)

[2021-04-14 13:01:40] production.ERROR: SQLSTATE[HY000] [2002] Connection timed out (SQL: SELECT * FROM `list` LIMIT 1) (View: /opt/app-root/src/resources/views/err1.blade.php) {"exception":"[object] (Facade\Ignition\Exceptions\ViewException(code: 0): SQLSTATE[HY000] [2002] Connection timed out (SQL: SELECT * FROM `list` LIMIT 1)

Then I see “504 Gateway Time-out The server didn’t respond in time.” Error. How do I configure eloquent so a database timeout throws a regular exception? (so the handler can show a more appealing standdard error page)

I tried to set the PDO options to PDO::ERRMODE_EXCEPTION in config/database.php and then php artisan config:clear but it did not work.

        'mysql' => [ 
                'driver' => 'mysql', 
                'host' => env('DB_HOST', 'forge'), 
                'port' => env('DB_PORT', '3306'), 
                'database' => env('DB_DATABASE', 'forge'), 
                'username' => env('DB_USERNAME', 'forge'), 
                'password' => env('DB_PASSWORD', ''), 
                'charset' => 'utf8', 
                'collation' => 'utf8_unicode_ci', 
                'prefix' => '', 
                'strict' => false, 
                'engine' => null, 
                'options'   => [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,]
                ],

Advertisement

Answer

The reason you are getting a 504 Gateway Time-out error is because when you perform a query with a database that does not exist, it takes a very long time (around 2mins for me).

I suspect your max execution time by your web-server or php config is lower than that, and therefore generates a 504 Gateway Time-out error.

There is 2 ways to fix this:

Increase your max-execution time in your server & PHP config

Increase your max execution time in your server by adjusting your server config file:

Also increase your max_execution_time time in your php.ini file (make sure to change the one used by the web-server, not just the CLI one). or add this at the start of index.php:

ini_set('max_execution_time', 1200); // 1200 seconds

Reduce the PDO timeout value

Use the following options:

 'options'   => [PDO::ATTR_TIMEOUT=> 10, // timeout in seconds]

Note that the actual timeout was often larger than the specified timeout for some reason. My tests showed that having a timeout of 10 seconds, actually timed out at 40sec. And 20 seconds timed out at 80sec. I don’t know why this is. Your experience may vary.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement