Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rainbowhat's avatar

Catching PDO Exception

Any proper way to catch PDO exceptions? If database server fails and laravel cant connect to it. Anyway I can display a custom page like error 500 or something.

The page will return a error 500 but already created a error 500 page. Seems like error 404 works well.

0 likes
5 replies
zOxta's avatar

You can just create a custom 500 error page at resources/views/errors/500.blade.php That page should be served on all 500 errors.

If you want to catch PDO exceptions in particular, you can either wrap your code in a try/catch block like:

        try {
            # your code should be here
            
        } catch (\PDOException $e) {
            # do something or render a custom error page
            
        }

Or you can generalize that by editing app/Exceptions/Handler.php to add the following block at the very top of the render() method:

    public function render($request, Exception $e)
    {
        if ($e instanceof \PDOException) {
            # do something special or render a custom error
        }
        .
        .
        .
    }
misiek303's avatar

try/catch does not work for me, what I do wrong...

PDOException in Connector.php line 55: SQLSTATE[42000] [1049] Unknown database 'test'
try
        {
            DB::connection()->getDatabaseName();

            //self::$instance = new static();
            self::$r = \Illuminate\Database\Eloquent\Model::getConnectionResolver();

            $settings = array(
                'driver'    => 'mysql',
                'host'      => env('DB_DATA_HOST', '127.0.0.1'),
                'database'  => $databasename,
                'username'  => $username,
                'password'  => $password,
                'charset'   => 'utf8',
                'collation' => 'utf8_unicode_ci',
                'prefix'    => '',
                'strict'    => false
            );

            $container = new Container;
            $connFactory = new ConnectionFactory($container);
            $conn = $connFactory->make($settings);
            $resolver = new \Illuminate\Database\ConnectionResolver();
            $resolver->addConnection('default', $conn);
            $resolver->setDefaultConnection('default');
            \Illuminate\Database\Eloquent\Model::setConnectionResolver($resolver);

            return $conn;
        }
        catch(\PDOException $e)
        {
            echo $e->getMessage();
        }

        catch(Exception $e)
        {
            echo $e->getMessage();
        }

        return null;

I tried also

catch(PDOException $e)

This worked but I need to catch it in model and return false if there is a db problem . I don't want to redirect to whoops page...

public function render($request, Exception $e)
 {
        if($e instanceof \PDOException )
        {
            return response()->view('errors.500', [], 500);
        }
        return parent::render($request, $e);
 }

Looks like my laravel5 overwrites php.ini settings - I confirmed below configuration under phpinfo() on different none laravel project

display_errors  On
error_reporting 22527

Laravel5 ?????? - why ?

display_errors  Off
error_reporting -1

I cannot even catch simple error

try
        {
            return $conn;
        }
        catch(\PDOException $e)
        {
            echo $e->getMessage();
        }

        catch(Exception $e)
        {
            echo $e->getMessage();
        }

        return null;

Results

ErrorException in DataModel.php line 36: Undefined variable: conn
Kerren's avatar

I know this is going to sound crazy but I think it wasn't working because you didn't have the backslash before Exception. For anyone reading this, I kept on getting PDOExceptions throw even though I was catching them?!

Anyways, it turns out that there is a difference between:

try {
    // code here
} catch (PDOException $e) {
    // code here
}

and

try {
    // code here
} catch (\PDOException $e) {
    // code here
}

Once I added that backslash it was all fine XD! I assume this also applies for normal Exeptions as well.

jlrdw's avatar

It has to do with namespacing, even using getPdo() with a fetch

$results = $sth->fetchAll(\PDO::FETCH_ASSOC);

you put a \ in front of pdo.

Please or to participate in this conversation.