我制作了服务器 API 来验证 Nuxt 上的一些数据,如下所示:
export default defineEventHandler(async (event) => {
const body = await readBody(event);
const result = schema.safeParse(body);
if (result.success === false) {
const error = result.error;
const customError = createError({
statusCode: 412,
statusMessage: `${error.errors[0].path} ${error.errors[0].message}`,
});
throw customError;
}
return { ok: true };
});
因此,当我输入错误时,createError 函数会被调用,并且我会得到如下返回:
{
"url": "/api/car/listings",
"statusCode": 412,
"statusMessage": "make Required",
"message": "make Required",
"stack": "<pre><span class=\"stack internal\">at createError (/H:/nuxt/cartrader/node_modules/h3/dist/index.mjs:48:15)</span>\n<span class=\"stack\">at /H:/nuxt/cartrader/.nuxt/dev/index.mjs:794:25</span>\n<span class=\"stack internal\">at process.processTicksAndRejections (node:internal/process/task_queues:95:5)</span>\n<span class=\"stack internal\">at async Object.handler (/H:/nuxt/cartrader/node_modules/h3/dist/index.mjs:723:19)</span>\n<span class=\"stack internal\">at async Server.toNodeHandle (/H:/nuxt/cartrader/node_modules/h3/dist/index.mjs:798:7)</span></pre>"
}
问题是如何删除错误响应中的堆栈字段,因为在 JSON 响应中使用该堆栈字段有点烦人,尤其是如果您想与其他人共享该 api 时?我尝试像这样删除它:
const customError = createError({
statusCode: 412,
statusMessage: `${error.errors[0].path} ${error.errors[0].message}`,
});
delete customError.stack;
throw customError;
但它只删除堆栈字段内的内容,并且它本身的字段仍然存在
{
"url": "/api/car/listings",
"statusCode": 412,
"statusMessage": "make Required",
"message": "make Required",
"stack": "<pre></pre>"
}
对此做了一些研究。显然它只包含堆栈字段如果服务器处于开发模式。所以这不会添加到生产中。
如果它确实在开发中困扰您,最干净的“修复”(本质上与
delete
相同),您可以这样做:
throw createError({
statusCode: 412,
statusMessage: `${error.errors[0].path} ${error.errors[0].message}`,
stack: undefined,
});