nuxt
Version:
[](https://nuxt.com)
61 lines (60 loc) • 2.46 kB
JavaScript
import { joinURL, withQuery } from "ufo";
import { getRequestHeaders, setResponseHeader, setResponseStatus } from "h3";
import { useNitroApp, useRuntimeConfig } from "#internal/nitro";
import { isJsonRequest, normalizeError } from "#internal/nitro/utils";
export default (async function errorhandler(error, event) {
const { stack, statusCode, statusMessage, message } = normalizeError(error);
const errorObject = {
url: event.node.req.url,
statusCode,
statusMessage,
message,
stack: process.dev && statusCode !== 404 ? `<pre>${stack.map((i) => `<span class="stack${i.internal ? " internal" : ""}">${i.text}</span>`).join("\n")}</pre>` : "",
data: error.data
};
if (error.unhandled || error.fatal) {
const tags = [
"[nuxt]",
"[request error]",
error.unhandled && "[unhandled]",
error.fatal && "[fatal]",
Number(errorObject.statusCode) !== 200 && `[${errorObject.statusCode}]`
].filter(Boolean).join(" ");
console.error(tags, errorObject.message + "\n" + stack.map((l) => " " + l.text).join(" \n"));
}
if (event.handled) {
return;
}
setResponseStatus(event, errorObject.statusCode !== 200 && errorObject.statusCode || 500, errorObject.statusMessage);
if (isJsonRequest(event)) {
setResponseHeader(event, "Content-Type", "application/json");
event.node.res.end(JSON.stringify(errorObject));
return;
}
const isErrorPage = event.node.req.url?.startsWith("/__nuxt_error");
const res = !isErrorPage ? await useNitroApp().localFetch(withQuery(joinURL(useRuntimeConfig().app.baseURL, "/__nuxt_error"), errorObject), {
headers: getRequestHeaders(event),
redirect: "manual"
}).catch(() => null) : null;
if (!res) {
const { template } = process.dev ? await import("@nuxt/ui-templates/templates/error-dev.mjs") : await import("@nuxt/ui-templates/templates/error-500.mjs");
if (process.dev) {
errorObject.description = errorObject.message;
}
if (event.handled) {
return;
}
setResponseHeader(event, "Content-Type", "text/html;charset=UTF-8");
event.node.res.end(template(errorObject));
return;
}
const html = await res.text();
if (event.handled) {
return;
}
for (const [header, value] of res.headers.entries()) {
setResponseHeader(event, header, value);
}
setResponseStatus(event, res.status && res.status !== 200 ? res.status : void 0, res.statusText);
event.node.res.end(html);
});