panthro
panthro

Reputation: 24061

How to catch errors and best practices?

I'm performing various tasks on an eloquent model.

e.g.

Flight Repository

function store($request){

    $flight = new Flight;

    $flight->name = $request->name;

    $flight->save();
}

This method is called from a controller:

public function store(FlightRepository $flight, $request){

    $flight->store($request);

}

How should one approach potential errors? try/catch? Where should it be placed in the controller or repository? What would I catch anyway, what exception type?

Upvotes: 1

Views: 3859

Answers (1)

Saumya Rastogi
Saumya Rastogi

Reputation: 13703

According to Laravel 5.0 and above,

All the Exceptions thrown in any part of the Laravel App, the exceptions are catched inside the report() method of Exception/Handler.php file, like this:

UPDATED

Your Repo should throw an Exception like this:

class CustomRepository extends Repository
{
    public function repoMethod($id)
    {
      $model = Model::find($id);

      // Throw your custom exception here ...
      if(!$model) {
          throw new CustomException("My Custom Message");
      }
    }
}

And your Handler should handle the CustomException like this:

/**
 * Report or log an exception.
 *
 * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
 *
 * @param  \Exception  $exception
 * @return void
 */
public function report(Exception $exception)
{
    // Handle your exceptions here...
    if($exception instanceof CustomException)
       return view('your_desired_view')->with('message' => $exception->getMessage());
    parent::report($exception);
}

Hope this helps!

Upvotes: 1

Related Questions