Coder Social home page Coder Social logo

jebbarbas / firebase-error-translator Goto Github PK

View Code? Open in Web Editor NEW
21.0 2.0 11.0 284 KB

Helps to handle the firebase errors based on their codes, you can translate the error to any of the available languages.

License: MIT License

TypeScript 47.07% JavaScript 52.93%

firebase-error-translator's Introduction

fet

Firebase Error Translator

Helps to handle the firebase errors based on their codes, you can translate the error to any of the available languages, now it also adds a translation to the client.


Build Status Libraries.io dependency status for latest release npm npm GitHub Repo stars

Services

For now, the version only supports translations for:

  • Auth: ✅
  • Storage: ✅
  • Firestore: ❌ (in the future, when I could find a documentation for the firestore errors)

Because new features are added, now it can only translate to 2 langs: English 'en', and Spanish 'es'; this is because that are the languages that I know how to write some phrases that explain the errors.

Basic Use

Note: This syntax is using module imports, but if you want to use commonjs modules, you can use them.

To use the function, import the translate function, and a TranslateDictionary, deppending on the service of the error and the language you want to translate; in this case the service of the possible error is Auth (firebase/auth), and the language I want to translate is spanish (es)

import { translate, AuthEs } from 'firebase-error-translator'

...

const registerUser = async (email, password) => {
    try{
        await signInWithEmailAndPassword(email, password)
    }
    catch(err){
        handleError(translate(err, AuthEs))
    }
}

...

translate will search the FirebaseError code in the given TranslateDictionary, and will return a TranslateObject, which has the properties toDev with a explained translation, and toClient, for ocassions where you want to show the error to the user (don't worry, not all errors display a detailed message).

...
// Lets asume that the error code is 'auth/user-not-found'
const translation = translate(err, AuthEs)

// Show the explained error to the developer
console.error(translation.toDev) // No existe ningún registro de usuario que corresponda al identificador proporcionado.

// Show a little hint of the error to the client
todoShowError(translation.toClient) // Usuario no encontrado, por favor revise su información.

In some cases, translation.toClient will return a detailled message like 'The provided email is taken by another user, please write another one.', and in another ocassions, it will only return a message like 'Server Error.', it deppends of the error.

...
// Lets asume now that the error code is 'auth/claims-too-large'
const translation = translate(err, AuthEn) // Note: Now we are using AuthEn instead of AuthEs, to get english translations

// Show the explained error to the developer
console.error(translation.toDev) // The claims payload provided to setCustomUserClaims() exceeds the maximum allowed size of 1000 bytes.

// Show a little hint of the error to the client
todoShowError(translation.toClient) // Server Error.

Multiple Dictionaries

If you don't know exactly what type of error are you getting (maybe in some function that can fail getting your auth and a storage), you can provide many TranslationDictionaries as you want.

...
const veryConfusingFunction = async () => {
    try{
        const userPhoto = await getUserPhoto() // Here can fail the auth service
        await uploadPhoto(userPhoto) // Here can fail the storage service
    }
    catch(err){
        // We provide 2 dictionaries because we don't know
        // in which function will fail
        handleError(translate(err, AuthES, StorageES))
    }
}

Custom Errors and Not Error Handling

If you want to force an error, you can make it with fail(), you only need to write the language of the error, the developer message and the client message.

import { fail, translate, AuthEN } from 'firebase-error-translator'

...

const loadForm = () => {
    try{
        if(email === ''){
            fail('en', 'The user didnt write its email, what a dumb.', 'Email is required, please write it:).')
        }
    }
    catch(err){
        const translation = translate(err, AuthEN)

        console.error(translation.toDev) // The user didnt write its email, what a dumb.
        todoShowError(translation.toClient) // Email is required, please write it:).
    }
}

You can also use translate with normal errors and values with toString() methods.

...

const failWithError = () => {
    try{
        throw new Error('My function failed.')
    }
    catch(err){
        console.log(translate(err, StorageES)) // We must provide at least one dictionary, this is to detect the language, the storage dictionaries are the shortest so we gonna use them

        /*
         * {
              toClient: 'Error de Servidor.',
              toDev: 'My function failed.',
         * }
         */
    } 
}

const failWithToString = () => {
    try{
        throw new Date()
    }
    catch(err){
        console.log(translate(err, StorageES)) // We must provide at least one dictionary, this is to detect the language, the storage dictionaries are the shortest so we gonna use them

        /*
         * {
              toClient: 'Error de Servidor.',
              toDev: '2022-07-29T02:51:51.246Z',
         * }
         */
    } 
}

TranslationDictionaries

The translation dictionaries are objects that start with the Firebase service of the codes that it contains (Auth or Storage right now), following by the language code based in the ISO 639-1 rules.

firebase-error-translator's People

Contributors

chrisjamesc avatar jebbarbas2 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

firebase-error-translator's Issues

Dynamic loading does not work with Metro (React-Native)

Great idea to have auth error messages translated into several languages!
Unfortunately, out of the box the library doesn't work for react native due to dynamic loading of the language files.

For now, I just used the translation files by importing them directly into my app.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.