用于API请求不存在对象的全局异常处理程序



我使用的是Laravel 5.3。我有几个api,其中用户将请求特定的id。例如url来订阅事件
example.com/api/event/{id}/subscribe

正常情况下,如果id不存在,Laravel将返回响应500,错误信息为"试图获取非对象的属性"

所以我将添加检查事件是否存在,在每个控制器中,模型'id' id传递:

$event = Event::find($id)
if ($event) {
    // return json data
}
else {
    return response()->json([
        'status' => 'object not found'
    ], 404);
}

我的问题是,有没有更好的解决方案来处理这个全局检查对象请求是否不存在?我目前的解决方案在这里,但我可能认为应该有更好的一个

我将此代码添加到我的app/Exception/Handler.php中,因此每个api请求不存在的对象将返回带有特定json消息的404。因此,API消费者将知道对象id无效。

public function render($request, Exception $exception)
{
    // global exception handler if api request for non existing object id
    if ($request->wantsJson() && $exception->getMessage() == 'Trying to get property of non-object') {
        return response()->json([
            'status' => 'object requested not found'
        ], 404);
    }
    return parent::render($request, $exception);
}

提前感谢!

可以使用AppExceptionsHandler类的render()函数:

public function render($request, Exception $exception)
{
    if ($request->wantsJson() && $exception instanceof ModelNotFoundException) {
        return response()->json(['status' => 'object requested not found'], 404);
    }
    return parent::render($request, $exception);
}

并记住添加以下代码:

use IlluminateDatabaseEloquentModelNotFoundException;

文档

尝试更改

$event = Event::find($id)

$event = Event::findOrFail($id)

据我所知,它会抛出一个ModelNotFoundException,如果它找不到任何id。转到app/Exceptions/Handler.php,在渲染方法中,捕获异常并处理它。

编辑:

if ($e instanceof HttpResponseException) {
            return $e->getResponse();
        } elseif ($e instanceof ModelNotFoundException) {
            $e = new NotFoundHttpException($e->getMessage(), $e);
        } elseif ($e instanceof AuthenticationException) {
            return $this->unauthenticated($request, $e);
        } elseif ($e instanceof AuthorizationException) {
            $e = new HttpException(403, $e->getMessage());
        } elseif ($e instanceof ValidationException && $e->getResponse()) {
            return $e->getResponse();
        }

您可以看到,如果父渲染方法获得ModelNotFoundException异常,则会触发NotFoundHttpException

最新更新