All files / src/utils errorHandler.ts

90.7% Statements 205/226
93.33% Branches 42/45
100% Functions 13/13
90.7% Lines 205/226

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292    1x   1x         1x 195x     195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x 195x     195x 12090x 195x   195x 195x                               1x   195x   195x   195x   195x   195x 195x 195x   1x 54x 3348x 54x 54x               1x 68x 68x 68x 68x 68x   68x 4216x 68x     68x   68x 66x     66x 62x 62x 62x 62x 62x 62x 62x 68x 2x   2x 2x 2x 2x 2x 2x 2x 2x 2x 68x   1x 69x 69x 69x   69x 69x 69x   69x 8x 8x 8x 8x 8x 8x   61x     61x 69x     69x 69x 69x 69x 69x 69x   1x 113x 113x 113x 113x 113x 5x 5x               5x 5x   113x 113x 7x 7x 7x 7x 7x 7x   7x 5x 5x 5x 5x 5x 5x 5x 113x 1x 1x               101x   1x 1x               1x 113x   1x 250x 250x         1x 250x 250x 250x 250x 250x 250x   1x 4x 4x 4x 1x 117x 117x 117x 1x 4x 4x 4x 1x 6x 6x 6x 1x 119x 119x 119x  
import type { CalloutType } from "@/utils/callout";
 
import { Ref, ref } from "vue";
 
import { toCalloutType } from "@/utils/callout";
 
export type ErrorStateMap = Record<string, Ref<boolean>>;
 
// Helper function to create error states with type safety
export function createErrorStateMap(): ErrorStateMap {
  const errorStateMap: ErrorStateMap = {};
 
  // Define all error state names
  const errorStateNames = [
    "apiErrorAppointmentCanNotBeCanceled",
    "apiErrorAppointmentNotAvailable",
    "apiErrorAppointmentNotFound",
    "apiErrorAuthKeyMismatch",
    "apiErrorCaptchaExpired",
    "apiErrorCaptchaInvalid",
    "apiErrorCaptchaMissing",
    "apiErrorCaptchaVerificationError",
    "apiErrorCaptchaVerificationFailed",
    "apiErrorDepartmentNotFound",
    "apiErrorEmailIsRequired",
    "apiErrorEmptyServiceArrays",
    "apiErrorInternalError",
    "apiErrorInvalidApiClient",
    "apiErrorInvalidAuthKey",
    "apiErrorInvalidCustomTextfield",
    "apiErrorInvalidDate",
    "apiErrorInvalidEmail",
    "apiErrorInvalidEndDate",
    "apiErrorInvalidFamilyName",
    "apiErrorInvalidLocationAndServiceCombination",
    "apiErrorInvalidOfficeId",
    "apiErrorInvalidProcessId",
    "apiErrorInvalidRequest",
    "apiErrorInvalidSchema",
    "apiErrorInvalidScopeId",
    "apiErrorInvalidServiceCount",
    "apiErrorInvalidServiceId",
    "apiErrorInvalidStartDate",
    "apiErrorInvalidTelephone",
    "apiErrorInvalidTimestamp",
    "apiErrorIpBlacklisted",
    "apiErrorMailNotFound",
    "apiErrorMismatchedArrays",
    "apiErrorNoAppointmentForThisDay",
    "apiErrorNoAppointmentForThisScope",
    "apiErrorNotFound",
    "apiErrorNotImplemented",
    "apiErrorOrganisationNotFound",
    "apiErrorPreconfirmationExpired",
    "apiErrorProcessAlreadyCalled",
    "apiErrorProcessAlreadyExists",
    "apiErrorProcessDeleteFailed",
    "apiErrorProcessInvalid",
    "apiErrorProcessNotPreconfirmedAnymore",
    "apiErrorProcessNotReservedAnymore",
    "apiErrorProviderNotFound",
    "apiErrorRateLimitExceeded",
    "apiErrorRequestDataTooLarge",
    "apiErrorRequestMethodNotAllowed",
    "apiErrorRequestNotFound",
    "apiErrorScopeNotFound",
    "apiErrorScopesNotFound",
    "apiErrorServiceUnavailable",
    "apiErrorSessionTimeout",
    "apiErrorSourceNotFound",
    "apiErrorTelephoneIsRequired",
    "apiErrorTooManyAppointmentsWithSameMail",
    "apiErrorUnknownError",
    "apiErrorZmsClientCommunicationError",
    "apiErrorInvalidJumpinLink",
    "apiErrorGenericFallback",
  ] as const;
 
  // Create refs for each error state
  errorStateNames.forEach((name) => {
    errorStateMap[name] = ref<boolean>(false);
  });
 
  return errorStateMap;
}
 
export interface ApiErrorTranslation {
  headerKey: string;
  textKey: string;
  errorType?: CalloutType;
}
 
export interface ApiErrorData {
  errorCode: string;
  errorType: CalloutType;
  errorMessage: string;
  statusCode: number;
}
 
// Centralized error state management
export function createErrorStates() {
  // Create error state map using helper function
  const errorStateMap = createErrorStateMap();
 
  return {
    // Individual error refs for direct access when needed
    ...errorStateMap,
    // Error state map for centralized operations
    errorStateMap,
    // Current error data for type information
    currentErrorData: ref<ApiErrorData | null>(null),
  };
}
 
export const clearContextErrors = (errorStateMap: ErrorStateMap) => {
  Object.values(errorStateMap).forEach((errorState) => {
    errorState.value = false;
  });
};
 
/**
 * Centralized error handler that maps API error codes to reactive error state variables
 * @param errorCode - The error code from the API response
 * @param errorStates - Object containing all reactive error state variables
 * @returns void - Sets the appropriate error state to true
 */
export function handleApiError(
  errorCode: string,
  errorStates: ErrorStateMap,
  currentErrorData?: Ref<ApiErrorData | null>,
  errorType?: CalloutType
): void {
  // Reset all error states first
  Object.values(errorStates).forEach((errorState) => {
    errorState.value = false;
  });
 
  // Dynamic error state mapping
  const errorStateKey = `apiError${errorCode.charAt(0).toUpperCase() + errorCode.slice(1)}`;
 
  if (errorStates[errorStateKey]) {
    errorStates[errorStateKey].value = true;
 
    // Set the current error data with the error type from the API
    if (currentErrorData) {
      currentErrorData.value = {
        errorCode: errorCode,
        errorType: toCalloutType(errorType),
        errorMessage: "",
        statusCode: 400,
      };
    }
  } else {
    errorStates.apiErrorGenericFallback.value = true;
 
    if (currentErrorData) {
      currentErrorData.value = {
        errorCode: "genericFallback",
        errorType: "error",
        errorMessage: "An unknown error occurred.",
        statusCode: 520,
      };
    }
  }
}
 
export function getApiErrorTranslation(
  errorStates: ErrorStateMap,
  currentErrorData?: Ref<ApiErrorData | null>
): ApiErrorTranslation {
  // Find the first active error state
  const activeErrorState = Object.entries(errorStates).find(
    ([_, isActive]) => isActive.value
  );
 
  if (!activeErrorState) {
    return {
      headerKey: "apiErrorGenericFallbackHeader",
      textKey: "apiErrorGenericFallbackText",
      errorType: "error",
    };
  }
 
  const [errorStateName] = activeErrorState;
 
  // Use the stored error type if available, otherwise default to "error"
  const errorType =
    currentErrorData?.value?.errorType || ("error" as CalloutType);
 
  // Dynamic translation key generation
  return {
    headerKey: `${errorStateName}Header`,
    textKey: `${errorStateName}Text`,
    errorType,
  };
}
 
export function handleApiResponse(
  data: any,
  errorStates: ErrorStateMap,
  currentErrorData?: Ref<ApiErrorData | null>
): void {
  if (!data || typeof data !== "object" || Array.isArray(data)) {
    errorStates.apiErrorGenericFallback.value = true;
    if (currentErrorData) {
      currentErrorData.value = {
        errorCode: "genericFallback",
        errorType: "error",
        errorMessage: "An unknown error occurred.",
        statusCode: 520,
      };
    }
    return;
  }
 
  const firstError = data?.errors?.[0];
  if (firstError && firstError.errorCode) {
    handleApiError(
      firstError.errorCode,
      errorStates,
      currentErrorData,
      toCalloutType(firstError.errorType)
    );
    // Store the error data for type information
    if (currentErrorData) {
      currentErrorData.value = {
        errorCode: firstError.errorCode,
        errorType: toCalloutType(firstError.errorType),
        errorMessage: firstError.errorMessage || "",
        statusCode: firstError.statusCode || 400,
      };
    }
  } else if (data.errors && data.errors.length > 0) {
    errorStates.apiErrorGenericFallback.value = true;
    if (currentErrorData) {
      currentErrorData.value = {
        errorCode: "genericFallback",
        errorType: "error",
        errorMessage: "An unknown error occurred.",
        statusCode: 520,
      };
    }
  } else if (data.errors && data.errors.length === 0) {
    // Handle case where errors array exists but is empty
    errorStates.apiErrorGenericFallback.value = true;
    if (currentErrorData) {
      currentErrorData.value = {
        errorCode: "genericFallback",
        errorType: "error",
        errorMessage: "An unknown error occurred.",
        statusCode: 520,
      };
    }
  }
}
 
export function hasAnyApiError(errorStates: ErrorStateMap): boolean {
  return Object.values(errorStates).some((errorState) => errorState.value);
}
 
// Context-specific error detection methods
// Each method shows any error that occurs in that specific context
// The component determines which context is active based on the current state
export function hasContextError(
  errorStates: ErrorStateMap,
  context: string,
  activeContext?: string
): boolean {
  return hasAnyApiError(errorStates) && activeContext === context;
}
 
export const hasUpdateContextError = (
  errorStates: ErrorStateMap,
  activeContext?: string
) => hasContextError(errorStates, "update", activeContext);
export const hasConfirmContextError = (
  errorStates: ErrorStateMap,
  activeContext?: string
) => hasContextError(errorStates, "confirm", activeContext);
export const hasPreconfirmContextError = (
  errorStates: ErrorStateMap,
  activeContext?: string
) => hasContextError(errorStates, "preconfirm", activeContext);
export const hasCancelContextError = (
  errorStates: ErrorStateMap,
  activeContext?: string
) => hasContextError(errorStates, "cancel", activeContext);
export const hasInitializationContextError = (
  errorStates: ErrorStateMap,
  activeContext?: string
) => hasContextError(errorStates, "initialization", activeContext);