How to handle exceptions and error messages in Laravel 5?

When I get this error:

QueryException on line 620 Connection.php: SQLSTATE [23000]: integrity violation of restrictions: 1062 Duplicate record

can I handle it with my own flash error message:

Oops, it seems like something went wrong

+7
php exception-handling error-handling laravel laravel-5
source share
2 answers

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

1) Let the structure process them for you:

If you do not handle exceptions yourself, Laravel will handle them in the class:

App\Exceptions\Handler 

In the render method, you can capture the visualization of all the exceptions that the frame creates. So, if you want to do something when a specific exception occurs, you can change this method as follows:

 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 yourself:

You can handle exceptions yourself using try-catch blocks. For example, in the controller 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 define a general general approach for handling certain exceptions.

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

+11
source share

it works fine with me

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

All Articles