useAp2iErrorHandler.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { useNuxtApp } from '#app'
  2. /**
  3. * Composable for handling API errors, especially for organization-related errors
  4. */
  5. export const useAp2iErrorHandler = () => {
  6. const { $i18n } = useNuxtApp()
  7. /**
  8. * Process API error and extract meaningful error message
  9. * @param error - The error object from API response
  10. * @returns Processed error message
  11. */
  12. const processApiError = (error: unknown): string => {
  13. let errorMessage =
  14. "Une erreur s'est produite. Veuillez réessayer plus tard ou nous contacter directement."
  15. // Try to extract the specific error message from the API response
  16. if (
  17. error &&
  18. typeof error === 'object' &&
  19. 'data' in error &&
  20. error.data &&
  21. typeof error.data === 'object'
  22. ) {
  23. const errorData = error.data as { detail?: string }
  24. if (errorData.detail) {
  25. // Check if it's the specific error about organization already existing
  26. const organizationExistsRegex =
  27. /Handling ".*" failed: An organization named '(.+)' already exists in (.+)/
  28. const match = errorData.detail.match(organizationExistsRegex)
  29. if (match) {
  30. // Extract the organization name and city name and use the translation
  31. const organizationName = match[1]
  32. const cityName = match[2]
  33. const translationKey =
  34. "An organization named '%s' already exists in %s"
  35. const translatedMessage = $i18n.t(translationKey, [
  36. organizationName,
  37. cityName,
  38. ])
  39. errorMessage = translatedMessage as string
  40. } else {
  41. // For other errors, use translation if available, otherwise use the original message
  42. if (!errorData.detail) return errorData.detail
  43. // Remove the "Handling ... failed:" part if present
  44. let cleanedDetail = errorData.detail
  45. const handlingFailedRegex = /Handling ".*" failed: (.*)/
  46. const handlingMatch = cleanedDetail.match(handlingFailedRegex)
  47. if (handlingMatch) {
  48. cleanedDetail = handlingMatch[1]
  49. }
  50. errorMessage = ($i18n.t(cleanedDetail) || cleanedDetail) as string
  51. }
  52. }
  53. }
  54. return errorMessage
  55. }
  56. return {
  57. processApiError,
  58. }
  59. }