如何在Laravel 5中处理PDOException

时间:2015-12-28 15:08:34

标签: php laravel pdo eloquent laravel-5.1

我已将Exceptions / Handler.php修改为:

    <?php namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class Handler extends ExceptionHandler {

    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
    'Symfony\Component\HttpKernel\Exception\HttpException'
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $e
     * @return void
     */
    public function report(Exception $e)
    {
        return parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $e
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {

        if($e instanceof NotFoundHttpException)
        {
            return response()->view('errors/404');
        }

        elseif ($e instanceof ErrorException) {
            return response()->view('errors/404');
        }

        elseif ($e instanceof ModelNotFoundException) {
            return response()->view('error_log(message)ors/404');
        }

        elseif($e instanceof PDOException)
        {
            return Redirect::to('install.php');
        }

        elseif($e instanceof QueryException)
        {
            return Redirect::to('install.php');
        }

        else return response()->view('errors/error');


    }

尝试在应用程序发出PDOException时重定向到安装,但我只是得到一般错误视图(错误/错误 - 来自上面代码的最后一行)。

有没有办法专门缓存PDOException错误?

3 个答案:

答案 0 :(得分:1)

包括 使用PDOException;

public function render($request, Exception $e)
    {

        if($e instanceof PDOException)
        {
            return response()->view('errors/404');
        }

在异常/处理程序中 它对我有用

答案 1 :(得分:0)

我想我已经找到了解决方案:

刚刚放

use PDOException; 

答案 2 :(得分:0)

这对Laravel 5.3(位于Handler.php中的/app/Exceptions/文件的摘录)中的效果非常有用:

public function report(Exception $e)
{

    // Both this, and below, are needed
    if($e instanceof \PDOException) {
        return response()->view('errors/404');
    }

    return parent::report($e);
}

public function render($request, Exception $e)
{

    if($e instanceof \PDOException) {
        // TODO send me an email!
        Session::flash('messageclass', 'danger');
        Session::flash('message', trans('general.pdoexception'));
        return redirect()->back();
    }

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