如何捕捉错误和最佳实践?

How to catch errors and best practices?

我正在 eloquent 模型上执行各种任务。

例如

航班资料库

function store($request){

    $flight = new Flight;

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

    $flight->save();
}

此方法是从控制器调用的:

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

    $flight->store($request);

}

应该如何处理潜在的错误? try/catch?它应该放在控制器或存储库中的什么位置?无论如何我会捕获什么,什么异常类型?

根据Laravel 5.0及以上,

在Laravel App的任何部分抛出的所有异常,异常都在Exception/Handler.php文件的report()方法中被捕获,像这样:

已更新

您的 Repo 应该抛出这样的异常:

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");
      }
    }
}

你的 Handler 应该这样处理 CustomException

/**
 * 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);
}

希望对您有所帮助!