How to Handle Exceptions and Error Messages in Laravel 5?

不羁的心 提交于 2019-12-05 04:48:38

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

Hussain Ali

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