【发布时间】:2023-03-08 15:25:02
【问题描述】:
考虑以下类:
// entity/Account.ts
import { Entity, PrimaryGeneratedColumn, Column, BaseEntity, Index, CreateDateColumn, UpdateDateColumn } from 'typeorm'
import { Field, Int, ObjectType } from 'type-graphql'
@ObjectType()
@Entity()
export class Account extends BaseEntity {
@Field(() => Int)
@PrimaryGeneratedColumn()
id: number
@Field()
@Column({ length: 50, unique: true })
@Index({ unique: true })
accountIdentifier: string
@Field({ nullable: true })
@Column({ length: 100 })
name?: string
}
对应的解析器:
// AccountResolver.ts
@Resolver()
export class AccountResolver {
@Mutation(() => Account)
async addAccount(@Arg('options', () => AccountInput) options: AccountInput) {
try {
// if (!options.accountIdentifier) {
// throw new Error(`Failed adding account: the accountIdentifier is missing`)
// }
return await Account.create(options).save()
} catch (error) {
if (error.message.includes('Cannot insert duplicate key')) {
throw new Error(
`Failed adding account: the account already exists. ${error}`
)
} else {
throw new Error(`Failed adding account: ${error}`)
}
}
}
}
Jest 测试文件
// AccountResolver.test.ts
describe('the addAccount Mutation', () => {
it('should throw an error when the accountIdentifier is missing', async () => {
await expect(
client.mutate({
mutation: gql`
mutation {
addAccount(
options: {
name: "James Bond"
userName: "James.Bond@contoso.com"
}
) {
accountIdentifier
}
}
`,
})
).rejects.toThrowError('the accountIdentifier is missing')
})
accountIdentifier 字段是必填字段,当请求中缺少该字段时,应抛出描述性错误消息。但是,抛出的错误是:
“网络错误:响应不成功:收到状态码 400”
修改错误信息的正确方法是什么?我查看了type-graphql 和class-validators,并确保设置了validate: true,但它没有给出描述性错误。
编辑
在检查了 graphql playground 之后,默认情况下它确实显示了正确的错误消息。剩下的唯一问题是如何编写笑话测试以便它可以读取此消息:
{
"error": {
"errors": [
{
"message": "Field AccountInput.accountIdentifier of required type String! was not provided.",
感谢您能给我的任何帮助。
【问题讨论】:
标签: graphql apollo apollo-client apollo-server typegraphql