【问题标题】:Add more attributes in laravel exception handler在 laravel 异常处理程序中添加更多属性
【发布时间】:2020-01-26 07:28:43
【问题描述】:

我正在使用 laravel 构建一个 restful api,并向 laravel 异常处理程序添加更多自定义属性。寻找最好的方法来做到这一点。

我目前正在使用 Laravel 6,如果我将 Accept 标头设置为 application/json,则会以 json 格式返回异常。我仍然想保留关于 laravel 如何通过 render 方法处理异常的现有逻辑,如下所示:

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

当前方法仅在调试为 false 时返回消息。

{
    "message": "No query results for model [App\\Model]"
}

我想为现有异常和自定义异常的响应数据添加更多属性:

{
    "message": "No query results for model [App\\Model]",
    "type": "exception",
    "url": "link to api docs",
    "id": "#id of the request"
}

我不想重写 render() 中的所有逻辑,但想通过添加这些属性来保持原样。

【问题讨论】:

    标签: php laravel exception


    【解决方案1】:

    我用这个

    public function render($request, Exception $exception)
        {
            if ($exception instanceof ModelNotFoundException || $exception instanceof NotFoundExeptionMessage){
                return $this->NotFoundExeptionMessage($request, $exception);
            }
            return parent::render($request, $exception);
        }
    

    此代码检查错误并将其传递给 NotFoundExeptionMessage 如果标头设置 application/json 并且返回渲染 并在第二个

    public function NotFoundExeptionMessage($request, Exception $exception): JsonResponse
        {
            return $request->expectsJson()
                ? new JsonResponse([
                    'data' => 'Not Found',
                    'Status' => 'Error'
                ], 404)
                :        parent::render($request, $exception);
    
        }
    

    我检查请求是否需要 json 响应我们返回 json 消息 否则我们返回一个渲染 你可以自定义jsonresponse 祝你好运

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-29
      相关资源
      最近更新 更多