'How do I display error messages with firebase 9

The following code works, and I get an error back if there's an issue. Note, this is vue code. Hence the .value

import { getAuth, createUserWithEmailAndPassword } from 'firebase/auth'

const register = async () => {
  loading.value = true
  let response
  try {
    const auth = getAuth()
    response = await createUserWithEmailAndPassword(
      auth,
      form.value.email,
      form.value.password
    )
  } catch (err) {
    console.log(err.message)
  }
  loading.value = false

  return response
}

However, here's an example of what error.message returns:

Firebase: Password should be at least 6 characters (auth/weak-password).

My question. Is there a way to get a clean message back? By that, I mean without Firebase: and (auth/weak-password).

Or am I missing something here? Is there another way I'm supposed to deal with Firebases error object? Perhaps I'm supposed to take the error.code and write a custom message myself for every scenario?

Let me know if any other information is needed, and I'll update the question :)



Solution 1:[1]

I'm currently using helper function, but don't think it's the best solution. Is there any better one?

function getRefinedFirebaseAuthErrorMessage(errorMesssage: string): string {
  return errorMesssage
    .replace('Firebase: ', '')
    .replace(/\(auth.*\)\.?/, '');
}

Notice that to force Firebase 9 to return an error message as Firebase: {real, descriptive error message}. (auth/{code}). it is necessary to init it with errorMap option set to debugErrorMap:

import { FirebaseApp, initializeApp } from 'firebase/app';
import { Auth, initializeAuth, debugErrorMap } from 'firebase/auth';

const app: FirebaseApp = initializeApp(firebaseConfig);
const auth: Auth = initializeAuth(app, { errorMap: debugErrorMap });

Otherwise, Firebase will return only error codes.

Solution 2:[2]

import { getAuth, createUserWithEmailAndPassword } from 'firebase/auth'

const register = async () => {
  loading.value = true
  let response
  try {
   if(form.value.password.length <= 6 ){
     return "Password should be at least 6 characters (auth/weak-password)"
   }

    const auth = getAuth()
    response = await createUserWithEmailAndPassword(
      auth,
      form.value.email,
      form.value.password
    )
  } catch (err) {
    console.log(err.message)
  }
  loading.value = false

  return response
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ?ukasz Ciesielski
Solution 2 some freelancer