errors.ts 759 Bytes
import type { ErrorResponse } from '../../packages/contracts/src/index.js';

export class AppError extends Error {
  readonly code: string;
  readonly statusCode: number;
  readonly details?: unknown;

  constructor(code: string, message: string, statusCode = 400, details?: unknown) {
    super(message);
    this.name = 'AppError';
    this.code = code;
    this.statusCode = statusCode;
    this.details = details;
  }
}

export function isAppError(error: unknown): error is AppError {
  return error instanceof AppError;
}

export function createErrorResponse(
  code: string,
  message: string,
  requestId?: string,
  details?: unknown,
): ErrorResponse {
  return {
    error: {
      code,
      message,
      requestId,
      details,
    },
  };
}