Courses

PHP for Laravel Developers

Try-Catching Exceptions and PHP Errors

Summary of this lesson:
- Learn about try-catch block usage
- Understand custom exception creation
- Explore global exception handling
- Examine differences between exceptions and errors

Exceptions are the mechanism to catch some invalid behavior and gracefully handle them instead of just showing "500 server error" to the users.

Take a look at this example:

public function __invoke()
{
$data = [['name' => 'John Doe', 'email' => '[email protected]', 'date' => '23-04']];
 
try {
$this->import($data);
} catch (ImportHasMalformedData $e) {
return redirect()->route('dashboard')->with('message', 'Uh oh, the import has failed. Try again later or contact support');
}
 
return 'Imported';
}

This snippet means that in case of ANY Exception, the user would get redirected back and see the error message.

But what if we're expecting something specific to happen?


Catching a Specific Laravel Exception

Try-catch is way more helpful when catching a specific Exception. Laravel and 3rd party packages often offer...

The full lesson is only for Premium Members.
Want to access all 16 lessons of this course? (52 min read)

You also get:

  • 73 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord