You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何移除Laravel Lighthouse GraphQL响应中的locations与path字段

移除Laravel Lighthouse GraphQL错误响应中的locations和path字段

我在使用Laravel Lighthouse构建GraphQL API时,需要返回的错误响应仅保留errors中的message字段和data字段,移除默认的locations和path字段。

现有代码示例

public function doSomething($_, array $args, GraphQLContext $context, ResolveInfo $resolveInfo){
    $apples_count = $context->user()->apples;
    if($apples_count > 10){
      //do something
        return  [
            'success' => true
        ];
    }else{
        throw new Error('You must have more then 10 apples');
    }
}

当前错误响应

{
  "errors": [
    {
      "message": "You must have more then 10 apples",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "doSomething"
      ]
    }
  ],
  "data": {
    "doSomething": null
  }
}

已尝试创建自定义异常、设置APP_DEBUG=false/APP_ENV=production、配置LIGHTHOUSE_DEBUG=null|false|0,均未达到预期效果。

解决方案:自定义错误格式化器

1. 创建自定义错误格式化器类

在项目中创建app/GraphQL/ErrorFormatters/CustomErrorFormatter.php文件,实现Lighthouse的ErrorFormatter接口,仅返回message字段:

<?php

namespace App\GraphQL\ErrorFormatters;

use Nuwave\Lighthouse\Execution\ErrorFormatter;
use GraphQL\Error\Error;
use Illuminate\Contracts\Container\Container;

class CustomErrorFormatter implements ErrorFormatter
{
    public function __construct(protected Container $container) {}

    public function format(Error $error): array
    {
        return [
            'message' => $error->getMessage(),
        ];
    }
}

2. 注册格式化器

修改config/lighthouse.php配置文件,将error_formatter指定为自定义类:

'error_formatter' => \App\GraphQL\ErrorFormatters\CustomErrorFormatter::class,

修改后预期响应

{
  "errors": [
    {
      "message": "You must have more then 10 apples"
    }
  ],
  "data": {
    "doSomething": null
  }
}

内容的提问来源于stack exchange,提问作者slame1121

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 20:03:17