Laravel 5.8 中的异常处理

Exception Handling in Laravel 5.8

我有一个 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 包括渲染方法中定义的错误。

can I do that? and is it best practice to handle exception in laravel?

throw new ModelNotFoundException;

不是:

throw new Exception(ModelNotFoundException);

ModelNotFoundException 扩展了 Exception,它本身就是一个 Exception。