【问题标题】:how to return custom error on graphql with typeorm and apollo如何使用 typeorm 和 apollo 在 graphql 上返回自定义错误
【发布时间】:2020-09-26 11:30:29
【问题描述】:

您好,我正在尝试返回自定义错误 用户创建的示例并且电子邮件存在:

{
  "errors": [
    {
      "message": "The email exists",
      "statusCode": "400"
    }
  ],
  "data": null
}

我现在有这个:

我的 APP.TS

export async function startServer() {
  const app = express();
  const schema = await createSchema();
  useContainer(Container);
  const connection = await createConnection();
  const server = new ApolloServer({
    schema,
    context: ({ req, res }: any) => ({ req, res }),
  });
  server.applyMiddleware({ app });
  return app;
}

Resovler.TS

@Resolver()
export class CreateUserResolver {
  //dependency inject
  constructor(private readonly userService: UserService) {}

  //create User Mutaton
  @Mutation(() => User)
  async register(
    @Arg('data')
    data: RegisterInput,
  ): Promise<Partial<User> | Object> {
    const user = this.userService.findOrCreate(data);
    return user;
  }
}

输入:

@InputType()
export class RegisterInput {
  @Field()
  @IsEmail({}, { message: 'Invalid email' })
  email: string;

  @Field()
  @Length(1, 255)
  name: string;

  @Field()
  password: string;
}

服务:

constructor(
    @InjectRepository(User)
    private userRep: Repository<User>,
  ) {}

  async findOrCreate(data: Partial<User>): Promise<Partial<User> | Object> {
    let user = await this.userRep.findOne({ where: { email: data.email } });
    if (user) throw new Error('user already exists');
    data.password = await bcrypt.hash(data.password, 12);
    user = await this.userRep.save({
      ...data,
    });
    return user;
  }

目前我找到的唯一解决方案是使用:

if (user) throw new Error ('user already exists');

但我无法想象如何使用状态码或只返回错误消息而不是所有这些消息:

【问题讨论】:

    标签: typescript graphql typeorm


    【解决方案1】:

    你做对了。你应该坚持 Apollo 产生的错误,因为它是一个 graphql 标准。当然,您不想向最终用户显示堆栈跟踪。要为生产禁用堆栈跟踪,请将 debug: false 传递给 Apollo Server 构造函数。

    来源:https://www.apollographql.com/docs/apollo-server/data/errors/

    【讨论】:

      猜你喜欢
      • 2020-12-21
      • 1970-01-01
      • 2021-06-18
      • 2020-01-15
      • 2021-05-07
      • 2018-01-28
      • 1970-01-01
      • 2020-01-22
      • 2020-12-19
      相关资源
      最近更新 更多