Files
lg-cxdash-front/src/lib/http-util.ts

53 lines
1.6 KiB
TypeScript

import {NextResponse} from "next/server";
import {HttpError} from "@/lib/http-client";
import {clientEnv} from "@/lib/env.client";
import {NONE_HTTP_ERROR, UNKNOWN_HTTP_ERROR} from "@/const/commonConst";
export type ApiError = {
status: number
code: string
message: string
}
export const errorToResponse = (error: unknown) => {
if (error instanceof HttpError) {
const payload = error.data ?? { message: "서버에서 오류 응답을 받았습니다." }
return NextResponse.json(payload, { status: error.status })
}
return NextResponse.json(
{ message: "서버 내부 오류가 발생했습니다." },
{ status: 500 }
)
}
const isDev = clientEnv.ENV !== "prod"
export const apiError = (e: unknown): ApiError => {
if (e instanceof HttpError) {
const d = e.data as any
const code = typeof d?.code === "string" ? d.code : UNKNOWN_HTTP_ERROR
const message =
(typeof d?.detail === "string" && d.detail) ||
(typeof d?.message === "string" && d.message) ||
(typeof d?.errMessage === "string" && d.errMessage) ||
(typeof d === "string" && d) ||
`HTTP ${e.status}`
if (isDev) {
console.groupCollapsed(
`[API ERROR] ${e.status}${code ? ` / ${code}` : ""}`
)
console.log("url:", e.url)
if (e.traceId) console.log("traceId:", e.traceId)
console.log("raw data:", d)
console.groupEnd()
}
return { status: e.status, code, message }
}
if (isDev) console.error("[NON-HTTP ERROR]", e)
return { status: 500, code: NONE_HTTP_ERROR, message: "저장에 실패했습니다." }
}