46 lines
No EOL
1.7 KiB
TypeScript
46 lines
No EOL
1.7 KiB
TypeScript
import { Response } from "express";
|
|
import z from "zod";
|
|
import { ERROR_DEFINITIONS, ErrorKey } from "../stores/errorCodes";
|
|
import { Delay } from "cerceis-lib";
|
|
import { MAX_RETRY_COUNT, ROOP_DELAY_MS } from "../../serverConfig";
|
|
|
|
const CustomErrorSchema = z.object({
|
|
code: z.string(),
|
|
message: z.string(),
|
|
statusCode:z.number(),
|
|
});
|
|
|
|
export type CustomError = z.infer<typeof CustomErrorSchema>;
|
|
|
|
export const createCustomError = (key: ErrorKey): CustomError => {
|
|
const errorInfo = ERROR_DEFINITIONS[key];
|
|
return CustomErrorSchema.parse(errorInfo);
|
|
};
|
|
|
|
export const responseError = (error: any, res: Response | null = null) => {
|
|
if (!CustomErrorSchema.safeParse(error).success) {
|
|
console.error(error);
|
|
console.error("========== Unknown Error ==========");
|
|
if(res) return res.status(500).send('Internal Server Error');
|
|
}
|
|
const parsedError = CustomErrorSchema.parse(error);
|
|
console.error("========== Custom Error ==========");
|
|
console.error(`Error Code: ${parsedError.code}\n Message: ${parsedError.message}`);
|
|
if(res) return res.status(parsedError.statusCode).send(parsedError.message);
|
|
}
|
|
|
|
|
|
export const callFunctionWithRetry = async <T>(fn: () => Promise<T>): Promise<T | null> => {
|
|
for(let retryCount = 0; retryCount <= MAX_RETRY_COUNT; retryCount++) {
|
|
try {
|
|
const result = await fn();
|
|
if(!result) throw Error();
|
|
return result;
|
|
} catch(error) {
|
|
if(retryCount === MAX_RETRY_COUNT) return null;
|
|
console.warn(`\n\n========== リトライ${retryCount + 1}回目 ==========\n\n`);
|
|
await Delay(ROOP_DELAY_MS);
|
|
}
|
|
}
|
|
return null;
|
|
}; |