| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- import { useNuxtApp } from '#app'
- /**
- * Composable for handling API errors, especially for organization-related errors
- */
- export const useAp2iErrorHandler = () => {
- const { $i18n } = useNuxtApp()
- /**
- * Process API error and extract meaningful error message
- * @param error - The error object from API response
- * @returns Processed error message
- */
- const processApiError = (error: unknown): string => {
- const defaultErrorMessage =
- "Une erreur s'est produite. Veuillez réessayer plus tard ou nous contacter directement."
- // Try to extract the specific error message from the API response
- if (
- error &&
- typeof error === 'object' &&
- 'data' in error &&
- error.data &&
- typeof error.data === 'object'
- ) {
- const errorData = error.data as { detail?: string }
- if (errorData.detail) {
- // Check if it's the specific error about organization already existing
- const organizationExistsRegex =
- /An organization named '(.+)' already exists in (.+)/
- const match = errorData.detail.match(organizationExistsRegex)
- if (match) {
- // Extract the organization name and city name and use the translation
- const organizationName = match[1]
- const cityName = match[2]
- const translationKey =
- "An organization named '{0}' already exists in {1}"
- const translatedMessage = $i18n.t(translationKey, [
- organizationName,
- cityName,
- ])
- console.log(translatedMessage, organizationName, cityName)
- // Return only the translated message
- return translatedMessage as string
- } else {
- // Remove the "Handling ... failed:" part if present
- let cleanedDetail = errorData.detail
- const handlingFailedRegex = /Handling ".*" failed: (.*)/
- const handlingMatch = cleanedDetail.match(handlingFailedRegex)
- if (handlingMatch) {
- cleanedDetail = handlingMatch[1]
- }
- // Check if a translation exists for this error
- const translatedMessage = $i18n.t(cleanedDetail)
- // If we have a valid translation (not the same as the key), return only the translation
- if (translatedMessage !== cleanedDetail) {
- return translatedMessage as string
- }
- // Otherwise return the original error message
- return cleanedDetail
- }
- }
- }
- return defaultErrorMessage
- }
- return {
- processApiError,
- }
- }
|