How to use Try Catch exception in Laravel app

Exception handling is an integral part of any software development project. It helps you to anticipate and handle errors that may occur during runtime, making your application more reliable and user-friendly. In Laravel, the Try Catch block is a powerful exception handling mechanism that allows you to catch and handle exceptions that occur within your application.

In this blog post, we’ll discuss how to use the Try Catch exception in Laravel applications to handle exceptions effectively. We’ll cover everything from what exceptions are, to how to use Try Catch blocks to catch and handle them. By the end of this post, you’ll have a good understanding of how to use Try Catch blocks in your Laravel app to improve its reliability and robustness.

Let’s see an example below:

try {

  /* Write Your Code Here */

} catch (Exception $e) {

    return $e->getMessage();

}
<?php
    
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use App\Models\User;
use Exception;
    
class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        try {
            $user = User::find($input['id']);
        } catch (Exception $e) {
              
            $message = $e->getMessage();
            var_dump('Exception Message: '. $message);
  
            $code = $e->getCode();       
            var_dump('Exception Code: '. $code);
  
            $string = $e->__toString();       
            var_dump('Exception String: '. $string);
  
            exit;
        }
  
        return response()->json($user);
    }
}

Leave a Comment