How to Handle Exceptions and Error Messages in Laravel 5?

强颜欢笑 提交于 2019-12-22 05:03:02

问题


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");
}


来源:https://stackoverflow.com/questions/34250180/how-to-handle-exceptions-and-error-messages-in-laravel-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!