#Trying to set a header for an error response

1 messages · Page 1 of 1 (latest)

atomic spruce
#

When trying to implement RFC9457 using Nuxt, I am having a problem sending the content-type "application/problem+json" to an error response using sendError, as shown in the example below:

if (allQueries.length > 0 && !hasValidQueries) {
        setResponseHeaders(event, {
            'Content-Type': 'application/problem+json',
        });

        // event.headers.set('Content-Type', 'application/problem+json');

        // event.node.res.setHeader('Content-Type', 'application/problem+json');

        return sendError(event, createError({
            statusCode: 400,
            statusMessage: 'Invalid query',
            stack: event.context.clientAddress,
            data: {
                type: 'about:blank',
                title: 'Bad Request',
                status: 400,
                detail: 'You can only use group_id or group_name as query.',
                instance: event.path,
            }
        }))
}

None of the ways tried define the desired header, but if I comment out sendError and return a common message, like the example below, the header is defined.

if (allQueries.length > 0 && !hasValidQueries) {
        setResponseHeaders(event, {
            'Content-Type': 'application/problem+json',
        });

        return {
            test: 'Send Erro'
        }
}

Any idea what I should do to set a header using sendError?

unique nexus
#

It looks like sendError is a h3 internal function that probably shouldn't be used. And on this line it overwrites the content header https://github.com/unjs/h3/blob/c04c458810e34eb15c1647e1369e7d7ef19f567d/src/error.ts#L170

Docs say to throw createError https://h3.unjs.io/guide/event-handler#responses-types

GitHub

⚡️ Minimal H(TTP) framework built for high performance and portability - unjs/h3

atomic spruce
#

Firstly thanks for the help!

When I use sendError it is to obtain a JSON response in the request, because when using createError by launching directly I do not obtain a JSON response.

But I understand that the h3 documents do not have sendError documented, so there is no way to do this in Nuxt? To return an expected response in case of an error?

#

Or in this case should I use another means than createError? If you know what the option would be to obtain a JSON response I would greatly appreciate it.

unique nexus
#

when using createError by launching directly I do not obtain a JSON response
oh really? It should return json, are you using an API client like postman or are you using the browser?

So looking at the code I think if you throw creatError it will call sendError anyway and that overrides the content-type to be json.

So you could try making your own custom sendError that doesn't do this

export function customSendError(
  event: H3Event,
  error: Error | H3Error,
  debug?: boolean,
) {
  if (event.handled) {
    return;
  }

  const h3Error = isError(error) ? error : createError(error);

  const responseBody = {
    statusCode: h3Error.statusCode,
    statusMessage: h3Error.statusMessage,
    stack: [] as string[],
    data: h3Error.data,
  };

  if (debug) {
    responseBody.stack = (h3Error.stack || "").split("\n").map((l) => l.trim());
  }

  if (event.handled) {
    return;
  }
  const _code = Number.parseInt(h3Error.statusCode as unknown as string);
  setResponseStatus(event, _code, h3Error.statusMessage);
  // event.node.res.setHeader("content-type", MIMES.json);
  event.node.res.setHeader("content-type", "application/problem+json");
  event.node.res.end(JSON.stringify(responseBody, undefined, 2));
}
#

I hope this works for you. Just a little annoying that h3 overwrites your custom content-type header
Might even be good to open an issue or PR on this