【发布时间】: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