【问题标题】:Exception Handling in Laravel 5.8Laravel 5.8 中的异常处理
【发布时间】:2020-03-08 20:54:15
【问题描述】:

我有一个 VehicleController。在那里,我检查了来自路线的$request->vehicle。结果应该是汽车、火车或飞机。下面是代码。

我有合法的车辆阵列。

protected static $vehicle_arr = array('car', 'train', 'plane');

我会这样检查。

    private static function _isLegitimateVehicle($vehicle)
    {
        static::$_is_legitimate_vehicle = in_array($vehicle, static::$vehicle_arr);

        if (!static::$_is_legitimate_vehicle) {
            throw new Exception(ModelNotFoundException);
        }
    }

在那里,我抛出异常 ModelNotFoundException。

在 App\Exception\Handler.php 中,

public function render($request, Exception $exception)
    {
        return parent::render($request, $exception);

        if ($request->expectsJson()) {
            if ($exception instanceof ModelNotFoundException) {
                return response()->json([
                    'errors' => 'Model Not Found',
                ], Response::HTTP_NOT_FOUND);
            }
        }
    }

然后,在邮递员中,它的响应如下。 (这是因为throw new Exception 中的_isLegitimateVehicle()

{
     "message": "Use of undefined constant ModelNotFoundException - assumed 'ModelNotFoundException' (this will throw an Error in a future version of PHP)",
     "exception": "ErrorException"
}

我想响应 json,包括在渲染方法中定义的错误。

我可以这样做吗?在 laravel 中处理异常是最佳实践吗?

【问题讨论】:

    标签: json laravel exception response


    【解决方案1】:
    throw new ModelNotFoundException;
    

    不是:

    throw new Exception(ModelNotFoundException);
    

    ModelNotFoundException 继承了 Exception,它本身就是一个 Exception。

    【讨论】:

      猜你喜欢
      • 2014-04-22
      • 1970-01-01
      • 2020-04-24
      • 2019-10-17
      • 1970-01-01
      • 1970-01-01
      • 2020-09-14
      • 2015-02-18
      相关资源
      最近更新 更多