56 lines
1.7 KiB
TypeScript
56 lines
1.7 KiB
TypeScript
/**
|
|
* HTTP error helpers for consistent API responses.
|
|
*/
|
|
|
|
export class HttpError extends Error {
|
|
constructor(
|
|
public readonly statusCode: number,
|
|
message: string,
|
|
public readonly code?: string,
|
|
public readonly expose = true
|
|
) {
|
|
super(message);
|
|
this.name = 'HttpError';
|
|
}
|
|
}
|
|
|
|
/** Maps thrown errors to an HTTP status code. */
|
|
export function httpStatusForError(error: unknown): number {
|
|
if (error instanceof HttpError) return error.statusCode;
|
|
|
|
const code = (error as { code?: string })?.code;
|
|
if (code === 'EMAIL_NOT_VERIFIED') return 403;
|
|
if (code === 'WITHDRAWAL_2FA_REQUIRED') return 403;
|
|
if (code === 'WITHDRAWALS_DISABLED' || code === 'WITHDRAWAL_NETWORK_DISABLED') return 403;
|
|
if (
|
|
code === 'INSUFFICIENT_BALANCE' ||
|
|
code === 'HOT_WALLET_INSUFFICIENT_LIQUIDITY' ||
|
|
code === 'TRANSFER_MIN_REMAINING' ||
|
|
code === 'TRANSFER_LEDGER_ONLY'
|
|
) {
|
|
return 400;
|
|
}
|
|
if (code === 'DAILY_WITHDRAWAL_LIMIT_EXCEEDED') return 403;
|
|
if (code === 'WITHDRAWAL_NOT_FOUND') return 404;
|
|
if (
|
|
code === 'WITHDRAWAL_INVALID_TRANSITION' ||
|
|
code === 'WITHDRAWAL_LEGACY_READ_ONLY' ||
|
|
code === 'WITHDRAWAL_AWAITING_APPROVAL' ||
|
|
code === 'WITHDRAWAL_ALREADY_BROADCAST'
|
|
) {
|
|
return 409;
|
|
}
|
|
if (code === 'TOKEN_REVOKED') return 401;
|
|
if (code === 'ACCOUNT_LOCKED') return 429;
|
|
if (code === 'CAPTCHA_REQUIRED' || code === 'CAPTCHA_INVALID') return 400;
|
|
|
|
const msg = error instanceof Error ? error.message : String(error);
|
|
|
|
if (/Permission denied|Forbidden|not allowed/i.test(msg)) return 403;
|
|
if (/not found/i.test(msg)) return 404;
|
|
if (/virus scan|failed virus scan/i.test(msg)) return 422;
|
|
if (/Unauthorized|Invalid|required|Captcha|2FA|Password|Email|Account/i.test(msg)) return 400;
|
|
|
|
return 500;
|
|
}
|