useAp2iErrorHandler.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. const defaultErrorMessage =
  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. /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 '{0}' already exists in {1}"
  35. const translatedMessage = $i18n.t(translationKey, [
  36. organizationName,
  37. cityName,
  38. ])
  39. console.log(translatedMessage, organizationName, cityName)
  40. // Return only the translated message
  41. return translatedMessage as string
  42. } else {
  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. // Check if a translation exists for this error
  51. const translatedMessage = $i18n.t(cleanedDetail)
  52. // If we have a valid translation (not the same as the key), return only the translation
  53. if (translatedMessage !== cleanedDetail) {
  54. return translatedMessage as string
  55. }
  56. // Otherwise return the original error message
  57. return cleanedDetail
  58. }
  59. }
  60. }
  61. return defaultErrorMessage
  62. }
  63. return {
  64. processApiError,
  65. }
  66. }