1

what i am trying to do is if the connection to the database fails, instead of getting No connection could be made because the target machine actively refused it, i want to throw a custom view that displays a simple h1 with the text that the connection fails. How can i do that?

3 Answers 3

1

You can do this by modifying your app/Exceptions/Handler.php to catch that specific error:

public function render($request, Throwable $exception) {
    if ($exception instanceof QueryException) {
        return response()->view('errorpage');
    }

    return parent::render($request, $exception);
}

Of course you can change the QueryException to any exception that you want to handle, such as: Illuminate\Database\Eloquent\ModelNotFoundException or any other.

Sign up to request clarification or add additional context in comments.

Comments

1

In app/Exceptions/Handler.php

use PDOException;
use App\Exceptions\Handler;

class ExceptionHandler extends Handler
{
    public function render($request, Exception $exception)
    {
        if ($exception instanceof PDOException) {
            return response()->view('errors.database', [], 500);
        }

        return parent::render($request, $exception);
    }
}

In resources/views/errors, errors.database, you can create custom style

2 Comments

In my situation i didn't need use App\Exceptions\Handler, and instead of using Exception i used Throwable
@Raitiko Actually, I don't know the complete workaround, So I suggested what we commonly do. :)
0

The answer was given at the top, but i made it work with some modifications.

use Throwable;
use PDOException;

public function render($request, Throwable $exception)
{
    if ($exception instanceof PDOException) {
        return response()->view('errors.database', [], 500);
    }

    return parent::render($request, $exception);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.