Skip to content

Instantly share code, notes, and snippets.

@atrakeur
Created March 15, 2019 08:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atrakeur/5a6469823a130a73e1c13c0408367bfc to your computer and use it in GitHub Desktop.
Save atrakeur/5a6469823a130a73e1c13c0408367bfc to your computer and use it in GitHub Desktop.
export default {
"default": "Something went wong, please try again later. If the problem persist, please contact support team.",
"network": {
"default": "Network error, maybe your connection is down. Please try again later.",
},
"api": {
"default": "Something is wrong on our side, please try again later. If the problem persist, please contact support team",
"400": {
"default": "$t(errors.api.default)",
},
"401": {
"default": "Authorization required.",
"credentials": "Your login credentials are incorrect."
},
"422": {
"default": "$t(errors.api.default)",
"invalid-2FA": "Your SMS Token is invalid",
},
"500": {
"default": "$t(errors.api.default)",
"sms server down": "The SMS server isn't working on our side, please try again later or contact support.",
}
}
}
import { get, first, sortBy, filter, map, size, includes } from 'lodash'
const getErrorApiTranslation = (error, t) => {
const type = get(error, 'type', null)
const status = get(error, 'status', null)
const message = get(error, 'data.data.message', get(error, 'data.message', get(error, 'message', get(error, 'statusText', 'default'))))
// Handle net errors
if (type == 'error') {
return t('errors.network.default')
}
const apiErrors = t('errors.api', { returnObjects: true })
if (apiErrors[status]) {
const possibleMessages = filter(map(apiErrors[status], (value, key) => key), value => value !== "default")
const mostMatchingMessageKey = first(
sortBy(
filter(
possibleMessages,
value => {
const keyPart- = value.split('-')
return size(filter(keyParts, keyPart => includes(message, keyPart))) === 0
}
),
value => {
const keyPart- = value.split('-')
return size(filter(keyParts, keyPart => includes(message, keyPart)))
})
)
if (mostMatchingMessageKey) {
return t(`errors.api.${status}.${mostMatchingMessageKey}`)
}
return t(`errors.api.${status}`)
}
return t('errors.api.default')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment