using try catch in laravel

it’s important for a software to be able to handle errors effectively. it has to log the error and inform the user so he knows what’s the issue and decide what to do next.

in develpoing with laravel try-catch statement help us achieve this. it checks if the code give we are executing causes an error then catches that error and gives us the ability to take proper action.

try{
//do something

}catch(){

//log the error


}

Imagine we have a “Post” model and we want to update the “category_id” like this:

$category = Category::where('slug',request('slug'))->first();

$post->category_id = $category->id;

$post->save();

in this case, if a category with provided slug exists there won’t be any issue.

However if there is no category matching the slug user requested, then there is no $category model and then when we try to access $category->id an error will occur.

during development showing this exception is acceptable. but in production we usually set APP_DEBUG=false so a 500 error page shows up. However this does provide any helpful information to the user . we should show a proper message so user can understand what the issue is and of course we have to log the error so we understand what is happening in our software.

We place the what we want to achieve in the try{} statement and in the catch(){} block we specify the action we want to take in case of exeption happens:

    $post = \App\Models\Post::find(1);

    $category = \App\Models\Category::where('slug',  request('slug'))->first();

    try {
        $post->category_id = $category->id;

        $post->save();
        
    } catch (Exception $e) {
        //log the exception
        $msg = 'the category slug ' . request('slug') . ' does not exist.';
        Log::info($msg);

        //show a message to the user
        return $msg;
    }

in this example accessing the category id ($category->id) may cause an exception so we write it inside try{} block. Finally in the catch() block we log the exception and display a message to the user.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *