How to Handle Exceptions and Error Messages in Lar

2019-04-26 18:51发布

问题:

When i get this error:

QueryException in Connection.php line 620: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry

can i handle it with my own flash error message instead of:

Whoops, looks like something went wrong

回答1:

You have two ways to handle exceptions and show a custom response:

1) Let the framework handle them for you:

If you don't handle exceptions by yourself, Laravel will handle them in the class:

App\Exceptions\Handler

In the render method you can intercept the renderning of all the exceptions the framework rises. So, if you want to do something in particular when a specific exception rises, you can modify that method this way:

public function render($request, Exception $e)
{
    //check the type of the exception you are interested at
    if ($e instanceof QueryException) {

        //do wathever you want, for example returining a specific view
        return response()->view('my.error.view', [], 500);
    }

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

2) Handle the exceptions by yourself:

You can handle exceptions by yourself, with try-catch blocks. For example in a controller's method:

try
{
     //code that will raise exceptions
}
//catch specific exception....
catch(QueryException $e)
{
    //...and do whatever you want
    return response()->view('my.error.view', [], 500);    
}

The main difference between the two cases is that in case 1 you are defining a general, application-wide approach to handle specific exceptions.

On the other hand, in case 2, you can define exception hadling in specific points of your application



回答2:

This is work with me fine

if ($e instanceof \PDOException) {
    $dbCode = trim($e->getCode());
    //Codes specific to mysql errors
    switch ($dbCode)
    {
        case 23000:
            $errorMessage = 'my 2300 error message ';
            break;
        default:
            $errorMessage = 'database invalid';
    }
   return redirect()->back()->with('message',"$errorMessage");
}