From b72847ca6b1923d9ed2b42b152d3eb6d38c9f2a2 Mon Sep 17 00:00:00 2001
From: Jonah Husson <jonah@elixxir.io>
Date: Tue, 18 Feb 2020 00:43:10 +0000
Subject: [PATCH] Hotfix/error catch

---
 firebase/fcm.go                |  2 +-
 notifications/notifications.go | 15 ++++++++++++++-
 2 files changed, 15 insertions(+), 2 deletions(-)

diff --git a/firebase/fcm.go b/firebase/fcm.go
index 665e50a..9fb9a05 100644
--- a/firebase/fcm.go
+++ b/firebase/fcm.go
@@ -82,7 +82,7 @@ func sendNotification(app FBSender, token string) (string, error) {
 
 	resp, err := app.Send(ctx, message)
 	if err != nil {
-		return "", errors.Wrap(err, "Failed to send notification")
+		return resp, errors.Wrapf(err, "Failed to send notification.  Response: %+v", resp)
 	}
 	return resp, nil
 }
diff --git a/notifications/notifications.go b/notifications/notifications.go
index 0e20f00..ba31329 100644
--- a/notifications/notifications.go
+++ b/notifications/notifications.go
@@ -23,6 +23,7 @@ import (
 	"gitlab.com/elixxir/primitives/id"
 	"gitlab.com/elixxir/primitives/ndf"
 	"gitlab.com/elixxir/primitives/utils"
+	"strings"
 	"time"
 )
 
@@ -170,7 +171,19 @@ func notifyUser(fcm *messaging.Client, uid string, fc *firebase.FirebaseComm, db
 
 	resp, err := fc.SendNotification(fcm, u.Token)
 	if err != nil {
-		return "", errors.Errorf("Failed to send notification to user with ID %+v: %+v", uid, err)
+		// Catch two firebase errors that we don't want to crash on
+		// 403 and 404 indicate that the token stored is incorrect
+		// this means rather than crashing we should log and unregister the user
+		// Error documentation: https://firebase.google.com/docs/reference/fcm/rest/v1/ErrorCode
+		if strings.Contains(err.Error(), "403") || strings.Contains(err.Error(), "404") {
+			jww.ERROR.Printf("User with ID %+v has invalid token, unregistering...", uid)
+			err := db.DeleteUser(uid)
+			if err != nil {
+				return "", errors.Wrapf(err, "Failed to remove user registration for uid: %+v", uid)
+			}
+		} else {
+			return "", errors.Wrapf(err, "Failed to send notification to user with ID %+v", uid)
+		}
 	}
 	return resp, nil
 }
-- 
GitLab