How to report/propagate Firestore errors with call site context to recordError

101 Views Asked by At

I am using Firestore to persist data and all the examples of error handling in the Firestore docs and Google results essentially have the same particularly not rich pattern:

.setData(user.documentData) { error in
          if let error = error {
            print("Error writing user to Firestore: \(error)")
          }
        }

However, I'd like to add context about the call site (that I was trying to write the user, in the example above) to the error instead of getting the generic localized description FireStore error of writing data has failed when recording the error and propagating the error. For example:

.setData(user.documentData) { error in
          if let error = error {
            Crashlytics.sharedInstance().recordError(error)
            print("Error writing user to Firestore: \(error)")
            completion(.failure(error))
          }
        }

Is there a pattern to create a Swift custom error enum adhering to Error that inits with a Firestore error so as to retain its context and add the apps context of the error? Are there other approaches to providing local context info about what failed to write on a FireStore error?

1

There are 1 best solutions below

0
Scott On

I've implemented this based on SwiftBySundell's post, which seems to be suitable.

enum FireStoreError : Error {
  case userWriteError(String)
  ....
}

extension FireStoreError : LocalizedError {
  var localizedDescription : String? {
    switch self {
    case .userWriteError(let s): return NSLocalizedString("Unable to persist user: \(s)", comment: "")
    }
  }
}

.setData(user.documentData) { error in
          if let error = error {
            let userError = FireStoreError.userWriteError(error.localizedDescription)
            Crashlytics.sharedInstance().recordError(userError)
            completion(.failure(userError))
          }
        }