Furkan ozturk
Furkan ozturk

Reputation: 722

How to use try catch in this situation

I would like to delete other relations even if any of the previous deletions fail. I have used a lot of try/catch to achieve this. Is there a way I can reduce the amount of try-catch in my code or do it without try-catch?

    public function delete_live_event(Request $request){
        try{
            $user = User::find($request->auth_user_id);

            if(!$request->journey_item_id){
                return response()->json(['StatusMessage' => 'Bir hata oluştu !', 'StatusCode' => 401,'error'=>'live_event_id gönderilmedi'], 401);
            }
            $journey_item = JourneyItem::find($request->journey_item_id);
            if ($journey_item == null) {
                return response()->json(['StatusMessage' =>  __('contents.not_found'), 'StatusCode' => 404], 404);
            }

            /** Assigned Users deleted **/
            try{
                UserJourney::where('as_journey_id',$journey_item->journey->id)->delete();
            }catch (\Exception $e){ //log 
            }

            /** journey deleted **/
            try{
                $journey_item->journey()->delete();
            }catch (\Exception $e){
               //Log
            }

            /** content deleted **/
            try{
                $journey_item->content()->delete();
            }catch (\Exception $e){//Log
            }

            /** notifications deleted **/
            try{
                UserJourneyItemNotification::where('as_journey_item_id', $journey_item->id)->delete();
            }catch (\Exception $e){//Log
            }

            /** item deleted **/
            try{
                $journey_item->item()->delete();
            }catch (\Exception $e){//Log
            }

            /** journey_item deleted **/
            $journey_item->delete();

            return response()->json(['StatusMessage' => 'Live event is deleted succesfuly', 'StatusCode' => 200], 200);
        }catch (\Exception $e){
            //TODO error log
            return response()->json(['StatusMessage' => 'Bir hata oluştu !', 'StatusCode' => 400], 401);
        }
    }

Upvotes: 0

Views: 49

Answers (1)

Tim
Tim

Reputation: 273

Try / Catch is usually used in a situation where you want to catch an error in order to stop further processing. If the each of the items in your list can be deleted, even if the others cannot be deleted, then there is no reason to use try/catch at all.

You also do not need to wrap your main function in try/catch block, as the only failure that would occur within that code is if you called a method that did not exist in your object. That would be a code failure, which would require correction. This is not the type of error that you would want to allow processing to continue, as the missing method is a code bug and should be corrected.

Upvotes: 1

Related Questions