datasquirel/package-shared/functions/backend/serverError.ts

94 lines
2.6 KiB
TypeScript
Raw Normal View History

2024-11-06 06:26:23 +00:00
// @ts-check
2025-01-10 19:10:28 +00:00
import fs from "fs";
import { IncomingMessage } from "http";
type Param = {
user?: {
id?: number | string;
first_name?: string;
last_name?: string;
email?: string;
} & any;
message: string;
component?: string;
noMail?: boolean;
req?: import("next").NextApiRequest & IncomingMessage;
};
2024-11-06 06:26:23 +00:00
/**
2024-12-08 08:58:57 +00:00
* # Server Error
2024-11-06 06:26:23 +00:00
*/
2025-01-10 19:10:28 +00:00
export default async function serverError({
2024-11-06 06:26:23 +00:00
user,
message,
component,
noMail,
2024-12-06 10:31:24 +00:00
req,
2025-01-10 19:10:28 +00:00
}: Param): Promise<void> {
2024-12-06 10:31:24 +00:00
const date = new Date();
const reqIp = (() => {
if (!req) return null;
try {
const forwarded = req.headers["x-forwarded-for"];
const realIp = req.headers["x-real-ip"];
const cloudflareIp = req.headers["cf-connecting-ip"];
// Convert forwarded IPs to string and get the first IP if multiple exist
const forwardedIp = Array.isArray(forwarded)
? forwarded[0]
: forwarded?.split(",")[0];
const clientIp =
cloudflareIp ||
forwardedIp ||
realIp ||
req.socket.remoteAddress;
if (!clientIp) return null;
return String(clientIp);
} catch (error) {
return null;
}
})();
try {
let log = `🚀 SERVER ERROR ===========================\nError Message: ${message}\nComponent: ${component}`;
if (user?.id && user?.first_name && user?.last_name && user?.email) {
log += `\nUser Id: ${user?.id}\nUser Name: ${user?.first_name} ${user?.last_name}\nUser Email: ${user?.email}`;
}
2024-11-06 06:26:23 +00:00
2024-12-06 10:31:24 +00:00
if (req?.url) {
log += `\nURL: ${req.url}`;
}
2024-11-06 06:26:23 +00:00
2024-12-06 10:31:24 +00:00
if (req?.body) {
log += `\nRequest Body: ${JSON.stringify(req.body, null, 4)}`;
}
if (reqIp) {
log += `\nIP: ${reqIp}`;
}
log += `\nDate: ${date.toDateString()}`;
log += "\n========================================";
if (!fs.existsSync(`./.tmp/error.log`)) {
fs.writeFileSync(`./.tmp/error.log`, "", "utf-8");
}
const initialText = fs.readFileSync(`./.tmp/error.log`, "utf-8");
fs.writeFileSync(`./.tmp/error.log`, log);
fs.appendFileSync(`./.tmp/error.log`, `\n\n\n\n\n${initialText}`);
2025-01-10 19:10:28 +00:00
} catch (/** @type {any} */ error: any) {
2024-12-06 10:31:24 +00:00
console.log("Server Error Reporting Error:", error.message);
}
2025-01-10 19:10:28 +00:00
}
2024-11-06 06:26:23 +00:00
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////