1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Firebase ionic サインアップのエラータイプを判別して、アラート表示を変える

Last updated at Posted at 2019-10-10

はじめに

環境は以下の通り
・Firebaseの認証(メールアドレスとパスワード)
・ionic4

Firebase + ionicの認証をサクッと試してみる場合、こちらがオススメ。

サインアップ失敗の原因が文字制限とかの場合は、ReactiveFormsModuleなんかが使える。
参考

サインアップの時のエラーを判別する

Firebase認証でユーザーを新規登録する時に発生するエラーを、タイプ別に判別して表示したい。

「エラー」と一括りに言ってもエラータイプ(原因)は色々。
**まぁログインの時の方が圧倒的に複雑そうだが・・・**それは置いといて、、、

今回はサインアップの時に限定する!

エラーコードを取得

サインアップ時もし問題があれば、Firebaseさんからエラーの原因が返ってくる。
まずはそれをcatchする

 signup() {
    this.fireauth.auth.createUserWithEmailAndPassword(this.email, this.password)
      .then(res => {
     // サインアップ成功時の処理
        if (res.user) {
          console.log(res.user);
        }
      })
    // サインアップ失敗時の処理
      .catch(error => {
         console.log(error);
      });
  }

これでエラー内容をコンソールに出してみる。
もし、エラーの原因が同じメールアドレスが既に登録されている場合なら、こんな感じで返ってくる(あくまで2019年10月の時点で)

スクリーンショット 2019-10-10 20.16.01.jpg

その中の
code: "auth/email-already-in-use"を使うとしよう。

エラー内容によって出すアラートを変える

catchの部分をこうする

import { AlertController } from '@ionic/angular';

// 省略

constructor(
    private alertCtrl: AlertController
  ) { }

// 省略

 private showAlert(message: string) {
    this.alertCtrl
      .create({
        header: 'ユーザー登録失敗',
        message: message,
        buttons: ['OK']
      })
      .then(alertEl => alertEl.present());
  }

signup() {
    this.fireauth.auth.createUserWithEmailAndPassword(this.email, this.password)
      .then(res => {
     // サインアップ成功時の処理
        if (res.user) {
          console.log(res.user);
        }
      })
    // サインアップ失敗時の処理
     .catch(error => {
        console.log(error);
        const code = error.code;
        let message = 'エラーが発生しました。もう一度お試しください。。。';
        if (code === 'auth/email-already-in-use') {
          message = 'このメールアドレスは既に登録されています。。。';
        }
        this.showAlert(message);
      });
  }

もし同じメールアドレスが既に登録されている以外の理由でエラーが起こってるなら、'このメールアドレスは既に登録されています。。。'のアラートを出す。

これを応用すればログインの場合も使えるだろう:relieved:

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?