【发布时间】:2021-04-21 07:05:35
【问题描述】:
所以我有这个代码:
const getAllUsers = ({
Model, options,
}) => Model.find(options).catch((e) => {
throw e;
});
@ObjectType({ description: "User model" })
@Entity()
export class UserModel extends BaseEntity {
...
}
@ObjectType()
class Error {
constructor(data: {message: string, code: number}) {
this.message = data.message;
this.code = data.code;
}
@Field(() => Int)
code: number;
@Field(() => String)
message: string;
}
@ObjectType()
class Success {
@Field(() => [ UserModel ])
users: [UserModel];
}
const UserResponseType = createUnionType({
name: "UserResponseType",
types: () => [
Success,
Error,
] as const,
});
@Query(() => [ UserResponseType ])
async getAllUsers(): Promise<typeof UserResponseType> {
const errors = await Promise.resolve([
new Error({
code: 501,
message: "test",
}),
]);
const users = await getAllUsers({
Model: UserModel,
options: {
...
},
}).catch((e) => e);
return {
errors,
success: users,
};
}
我要做的就是返回错误或成功,以便我可以在查询中执行此操作:
query getAllUsers {
getAllUsers {
... on Success {
user {
id
email
}
}
... on Error {
code
message
}
}
}
但现在我得到了:
TS2322: Type '{ errors: Error[]; success: any; }' is not assignable to type 'Error | Success'.
Object literal may only specify known properties, and 'errors' does not exist in type 'Error | Success'.
我试图复制(https://typegraphql.com/docs/unions.html#docsNav)[这个例子) 那么如何才能实现上述的查询能力呢?
【问题讨论】:
-
为什么非标准错误处理?错误不应作为数据返回
-
现在这是一个很大的学习曲线的一部分。我应该如何返回错误?在 REST 中,我会将它们返回为
res.json({error:{code:5xx, message: "..."})。在 GraphQL 中我还能如何处理它?这也是我在网上找到的wjat -
优点/缺点...与中间件不兼容/记录/隐藏生产/等细节...apollographql.com/docs/apollo-server/data/errors...只是抛出一些错误类型的消息
-
@xadm 无法连接到数据库之类的异常?是的,只是抛出一个错误。像
UserAlreadyExists这样的域“错误”?使用专用的对象类型和联合返回类型,因此您在客户端的响应中有一个类型安全的 swich-case。
标签: javascript typescript graphql typegraphql