Are both error treatments the same?

Asked

Viewed 43 times

1

I have a great doubt regarding a visualized code regarding the handling of errors, I have 2 options for handling errors, one is being used a lot in a system that I am doing, and the other is the try and catch. Both examples are being made in PHP using framework Laravel.

First example:

 $variavel = Model::where('id',$id)->first()->delete(); 
    if($variavel){
        alert()->success('Sucesso!', ' removido com sucesso');
        return back();
    }else{
        alert()->error('Erro!', 'Erro ao remover!');
        return back();
    }

Now using the Try and the catch

try{
    Model::where('id',$id)->first()->delete(); 

    alert()->success('Sucesso!', ' removido com sucesso');
    return back();
}catch(Exception $e){
      alert()->error('Erro!', 'Erro ao remover!');
      return back();
}

Between the two examples, is there any difference regarding the handling of errors? Both are correct ways to do the handling of errors?

1 answer

-1

Central way to remove record with Laravel:

public function destroy($id){

   $model = Model::findOrFail($id);

   $model->delete();

   alert()->success('Sucesso!', ' removido com sucesso');

   return redirect()->back();   

}
  • Lucas, I use this form, but I’m doubtful about the handling of errors, for example, I cited two examples up there. I want to understand about these two forms that I cited if in question "handling errors" any of them differ in some situation.

  • Passes Findorfail in Try catch and uses throw to fix the bug

  • If you want I do two example one with throw and one with Session which is the shape I use

Browser other questions tagged

You are not signed in. Login or sign up in order to post.