import { ExceptionObject } from "./typings";
import { toISOLocal } from "../utils";
import { injectEvent } from "./injector";

export default class CfExceptionHandler {
  throwAndLogError(eventName: string, msg: string) {
    const error = new Error(msg);
    const exceptionObject: ExceptionObject = {
      title: msg,
      event_type: eventName,
      exception_type: error.name,
      exception_source: "JS-SDK",
      stack_trace: error.stack || "no stack",
      ts: toISOLocal(new Date()),
    };
    injectEvent("exception", eventName, exceptionObject, false, "");
    throw error;
  }

  throwAPIError(eventName: string, msg: string) {
    const error = new Error(msg);
    const exceptionObject: ExceptionObject = {
      title: msg,
      event_type: eventName,
      exception_type: error.name,
      exception_source: "JS-SDK",
      stack_trace: error.stack || "no stack",
      ts: toISOLocal(new Date()),
    };

    injectEvent("exception", eventName, exceptionObject, false, "");
  }

  throwNudgeFetchError(eventName: string, msg: string) {
    const error = new Error(msg);
    const exceptionObject: ExceptionObject = {
      title: msg,
      event_type: eventName,
      exception_type: error.name,
      exception_source: "JS-SDK",
      stack_trace: error.stack || "no stack",
      ts: toISOLocal(new Date()),
    };

    injectEvent("exception", eventName, exceptionObject, false, "");
  }
}
