Search code examples
nuxt.jsnuxt3

Remove stack field from Nuxt createError response


I made server API for validate some data on Nuxt like this :

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 };
});

so when i have bad inputs the createError function get called and i get some return like this :

{
    "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>"
}

the question is how can I remove that stack field in the error response because it is a bit annoying to have that in JSON response especially if you want share that api with others? I tried to remove it like this :

const customError = createError({
      statusCode: 412,
      statusMessage: `${error.errors[0].path} ${error.errors[0].message}`,
    });
    delete customError.stack;
    throw customError;

but it only remove content inside stack field and the field it self still exist

{
    "url": "/api/car/listings",
    "statusCode": 412,
    "statusMessage": "make Required",
    "message": "make Required",
    "stack": "<pre></pre>"
}

Solution

  • did some research on this. apparently it only includes the stack field if the server is in dev mode. so this won't be appended in production.

    if it does bother you in development, the cleanest 'fix' (which is essentially the same as delete), you can do this:

    throw createError({
      statusCode: 412,
      statusMessage: `${error.errors[0].path} ${error.errors[0].message}`,
      stack: undefined,
    });