93 lines
2.0 KiB
TypeScript
93 lines
2.0 KiB
TypeScript
import { HttpError } from "./http-client.js";
|
|
import { getServerMessage } from "./error-policy.js";
|
|
|
|
export const UNKNOWN_HTTP_ERROR = "UNKNOWN_HTTP_ERROR";
|
|
|
|
export const NONE_HTTP_ERROR = "NONE_HTTP_ERROR";
|
|
|
|
export type ApiError = {
|
|
status: number;
|
|
code: string;
|
|
message: string;
|
|
};
|
|
|
|
export type ApiErrorOptions = {
|
|
fallbackMessage?: string;
|
|
debug?: boolean;
|
|
};
|
|
|
|
export const apiError = (
|
|
error: unknown,
|
|
options: ApiErrorOptions = {},
|
|
): ApiError => {
|
|
const { fallbackMessage = "요청 처리에 실패했습니다.", debug = false } =
|
|
options;
|
|
|
|
if (error instanceof HttpError) {
|
|
const data = error.data as {
|
|
code?: unknown;
|
|
detail?: unknown;
|
|
message?: unknown;
|
|
errMessage?: unknown;
|
|
} | null;
|
|
|
|
const code =
|
|
typeof data?.code === "string" ? data.code : UNKNOWN_HTTP_ERROR;
|
|
|
|
const message =
|
|
(typeof data?.detail === "string" && data.detail) ||
|
|
getServerMessage(error.data) ||
|
|
(typeof data?.errMessage === "string" && data.errMessage) ||
|
|
`HTTP ${error.status}`;
|
|
|
|
if (debug) {
|
|
console.groupCollapsed(`[API ERROR] ${error.status} / ${code}`);
|
|
console.log("url:", error.url);
|
|
|
|
if (error.traceId) {
|
|
console.log("traceId:", error.traceId);
|
|
}
|
|
|
|
console.log("raw data:", error.data);
|
|
console.groupEnd();
|
|
}
|
|
|
|
return {
|
|
status: error.status,
|
|
code,
|
|
message,
|
|
};
|
|
}
|
|
|
|
if (debug) {
|
|
console.error("[NON-HTTP ERROR]", error);
|
|
}
|
|
|
|
return {
|
|
status: 500,
|
|
code: NONE_HTTP_ERROR,
|
|
message: fallbackMessage,
|
|
};
|
|
};
|
|
|
|
export const errorToResponse = (error: unknown): Response => {
|
|
if (error instanceof HttpError) {
|
|
const payload = error.data ?? {
|
|
message: "서버에서 오류 응답을 받았습니다.",
|
|
};
|
|
|
|
return Response.json(payload, {
|
|
status: error.status,
|
|
});
|
|
}
|
|
|
|
return Response.json(
|
|
{
|
|
message: "서버 내부 오류가 발생했습니다.",
|
|
},
|
|
{
|
|
status: 500,
|
|
},
|
|
);
|
|
};
|