Content-Type header not being set from plugin #1891
-
Hi everyone! Loving the DX of this so far, but I'm running into some issues. I'd like to catch any errors that are thrown in any route, so I've made a plugin to handle them: import httpStatus from "http-status";
import { APIException } from "~/responses/exceptions/api.exception";
import { BadRequestException } from "~/responses/exceptions/badRequest.exception";
export default defineNitroPlugin((nitro) => {
nitro.hooks.hook("error", async (error, { event }) => {
let response: any = {
isSuccess: false,
code: httpStatus.INTERNAL_SERVER_ERROR,
status: httpStatus[httpStatus.INTERNAL_SERVER_ERROR],
timestamp: new Date().toISOString(),
message: "Something went wrong, please try again later.",
};
if (error instanceof APIException) {
response = {
isSuccess: error.isSuccess,
code: error.code,
status: error.status,
timestamp: error.timestamp,
message: error.message,
};
if (error instanceof BadRequestException) {
response.errors = error.errors;
}
}
event.node.res.statusCode = response.code;
event.node.res.end(JSON.stringify(response));
event._handled = true;
});
}); I imagined that ending the response and marking the event as handled would work, but when this is run it completes successfully (sends what I'd expect to the frontend), but it also logs these two errors:
I can't find much more information about this, any ideas of something I'm doing wrong or is this a bug? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
I managed to muddle my way through that issue, but now the Content-Type is being sent as "text/html" and the status code isn't being set either. Nothing I do (calling import httpStatus from "http-status";
import { APIException } from "~/responses/exceptions/api.exception";
import { BadRequestException } from "~/responses/exceptions/badRequest.exception";
export default defineNitroPlugin((nitro) => {
nitro.hooks.hook("error", async (error, { event }) => {
if (error.cause instanceof APIException) {
error = error.cause;
}
let response: any = {
isSuccess: false,
code: httpStatus.INTERNAL_SERVER_ERROR,
status: httpStatus[httpStatus.INTERNAL_SERVER_ERROR],
message: "Something went wrong, please try again later.",
};
if (error instanceof APIException) {
response.id = event.context.requestId;
response.isSuccess = error.isSuccess;
response.code = error.code;
response.status = error.status;
response.message = error.message;
if (error instanceof BadRequestException) {
response.errors = error.errors;
}
}
setResponseStatus(event, response.code);
send(event, JSON.stringify(response), "application/json");
});
}); |
Beta Was this translation helpful? Give feedback.
-
Solved all of this by doing: event.respondWith(
new Response(JSON.stringify(response), {
status: response.code,
headers: {
"Content-Type": "application/json",
},
})
); |
Beta Was this translation helpful? Give feedback.
Solved all of this by doing: