jeudi 1 juin 2017

The proper way to do exception handling

in the laravel doc we see:

http://ift.tt/2suEp5s

public function report(Exception $exception)
{
    if ($exception instanceof CustomException) {
        //
    }

    return parent::report($exception);
}

Now what I generally do when writing code is something like this

function changeBookAuthor(int $id, string $newName){
  if(!$newName){
   throw new MyAppException('No author name was provided');
  }

  $book = Books::find($id);

  if(!$book){
   throw new MyAppException('The provided book id could not be found');
  }
}

Now how to I properly handle the exception? they are all the same exception and they have no code neither. Should I provide an error code? the problem with php exception is that they use integers. Is quite annoying imho. Better would be 'changeauthor_bookid_notfound' as code instead of a random number. Should I create an exception class for each single exception? e.g. not reuse MyAppException that seems a bit tedious. I would have a trillion classes.

Now if for a special exception I want special handling, with my code, I cannot easily do it. I have no code to check for (e.g. $exception->code == 3331 then do special) and I don't have custom exception classes neither

what is a proven good solid way to handle this case? code, new class on each error, something else all together?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire