Friday, February 8, 2019

Try catch not working Laravel raw queries | How to properly catch PHP exceptions (Laravel 5.X) | Why try catch not work in Laravel


Make sure you're using your namespaces properly. If you use a class without providing its namespace, PHP looks for the class in the current namespace. Exception class exists in global namespace, so if you do that try/catch in some namespaced code, e.g. your controller or model, you'll need to do catch(\Exception $e) to catch all your exceptions:  


try {
  //code causing exception to be thrown
}
catch(\Exception $e) {
  //exception handling
}


If you do it like this there is no way to miss any exceptions. Otherwise if you get an exception in a controller code that is stored in App\Http\Controllers, your catch will wait for App\Http\Controllers\Exception object to be thrown.

No comments:

Post a Comment