Lighthouse v6.10如何获取错误category?原v5.41可通过扩展获取
解决Lighthouse v6.10错误扩展丢失category字段的问题
Lighthouse v6.x重构了错误处理模块,默认移除了v5.x中错误扩展里的category字段。下面提供两种解决思路,适配你的需求:
方法1:自定义错误扩展,手动添加category字段
你可以通过注册自定义错误处理器,给所有GraphQL错误重新添加category字段,和v5.41的行为保持一致:
- 在
App\Providers\LighthouseServiceProvider的boot方法中添加如下代码:
use Nuwave\Lighthouse\Execution\ErrorHandler; use Nuwave\Lighthouse\Execution\Extensions\Extension; public function boot() { parent::boot(); $this->app->extend(ErrorHandler::class, function (ErrorHandler $handler) { return $handler->handle(function (\Throwable $throwable, array $context) { // 根据异常类型映射对应的category值 $category = match (true) { $throwable instanceof \Illuminate\Validation\ValidationException => 'validation', $throwable instanceof \Illuminate\Auth\AuthenticationException => 'authentication', $throwable instanceof \Illuminate\Authorization\AuthorizationException => 'authorization', // 按需添加其他异常类型的映射 default => 'internal' }; // 合并默认扩展字段与自定义的category return [ 'extensions' => new Extension([ 'category' => $category, ...$context['extensions']->toArray(), ]), ]; }); }); }
- 配置完成后,所有GraphQL错误的
extensions对象中就会包含category字段,前端无需修改即可继续使用原来的逻辑处理错误。
方法2:适配Lighthouse v6的标准错误标识
Lighthouse v6遵循GraphQL规范,改用code字段来标识错误类型,替代了原有的category。你可以直接在Apollo Client中通过code字段处理错误:
常见错误code映射:
UNAUTHENTICATED→ 原authenticationcategoryFORBIDDEN→ 原authorizationcategoryVALIDATION_ERROR→ 原validationcategoryINTERNAL_SERVER_ERROR→ 原internalcategory
前端(Apollo Client)处理示例:
import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client'; import { onError } from '@apollo/client/link/error'; const errorLink = onError(({ graphQLErrors }) => { if (graphQLErrors) { graphQLErrors.forEach(({ extensions }) => { const errorCode = extensions?.code; switch(errorCode) { case 'UNAUTHENTICATED': // 处理未认证逻辑,比如跳转登录页 break; case 'VALIDATION_ERROR': // 处理表单验证错误,比如提示用户输入问题 break; case 'FORBIDDEN': // 处理权限不足逻辑 break; default: // 处理其他内部错误 } }); } }); const httpLink = createHttpLink({ uri: '/graphql' }); const client = new ApolloClient({ link: errorLink.concat(httpLink), cache: new InMemoryCache(), });
注意事项
- 方法1适合需要快速兼容旧代码的场景,但需要维护异常类型与category的映射关系。
- 方法2是Lighthouse v6官方推荐的方式,符合GraphQL规范,长期维护性更强。
内容的提问来源于stack exchange,提问作者ali asghar sadat fakhr
相关产品推荐
相关产品推荐

