我有一个Nuxt前端和Strapi后端(基于Koa构建),并且正在使用GraphQL。我想添加卡错误处理,但是遇到了如何将完整的Stripe错误对象返回到前端的问题。
后端 ./ order / controllers / order.js:
'use strict';
require('dotenv').config();
const { nanoid } = require('nanoid');
const stripe = require('stripe')(`${process.env.STRIPE_SECRET_KEY}`);
module.exports = {
create: async ctx => {
const { amount, email, firstName, lastName, token } = ctx.request.body;
// charge the customer
try {
await stripe.charges.create({
// transform cents to dollars
amount: amount * 100,
currency: 'usd',
description: `Order ${new Date()} from ${firstName} ${lastName}`,
source: token,
});
// register the order in the database
try {
const order = await strapi.services.order.create({
amount,
email,
firstName,
lastName,
uid: nanoid()
});
return order;
} catch (err) {
console.log('order error: ', err);
}
} catch (err) {
console.log('stripe error: ', err);
ctx.response.status = 400;
ctx.response.message = err.raw.message;
ctx.response.body = err;
return ctx.response;
}
},
};
前端 cart.vue:
handleSubmit() {
this.submitting = true;
// create Stripe token, then pass to mutation
createToken()
.then(({ token }) => {
console.log('token: ', token);
// create order mutation
this.$apollo.mutate({
mutation: createOrderMutation,
variables: {
amount: this.amount,
email: this.email,
firstName: this.firstName,
lastName: this.lastName,
token: token.id
}
})
.then(({ data }) => {
console.log('data: ', data);
if (data.createOrder.order) {
this.clearCart();
this.$router.push('/thanks');
}
})
.catch(err => {
console.log('mutate err: ', err); <--- where I'm currently returning Stripe error
})
.then(() => this.submitting = false);
})
.catch(err => {
this.submitting = false;
console.error('stripe error: ', err);
})
.then(() => this.submitting = false);
},
看看与Koa documentation直接链接的Strapi documentation,我认为我可以直接设置ctx.response
属性,然后返回该响应,但是在前端,我得到的是Error: GraphQL error: Your card was declined.
,我想返回完整的错误对象,以便我可以更准确地告诉用户发生了什么类型的错误。任何帮助将不胜感激!