0

I have the following extension on URLSession class :

extension URLSession {

    @discardableResult
    func sendRequest<A>(endpoint: Endpoint<A>, onComplete: @escaping (Result<A?, Error>) -> ()) -> URLSessionDataTask {
        let task = dataTask(with: endpoint.request, completionHandler: { data, response, err in
            if let err = err {
                onComplete(.failure(err))
              return
            }
            if let da = data, let a = try? JSONDecoder().decode(APIError.self, from: da) {
                if a.error.message == "The username or password is wrong" {
                    onComplete(.failure(LoginErrors.uOrPincorrect))
                }
                if a.error.message == "Your account is locked" {
                    onComplete(.failure(LoginErrors.accountLocked))
                }
                return
            }
        task.resume()
        return task
    }
}

And then these structs and enums for Errors :

struct APIError: Decodable {
    let error: APIErrorMessage
}

struct APIErrorMessage: Decodable {
    let message: String
}


enum LoginErrors: String, Error {
    case uOrPincorrect = "The username or password you entered is/are wrong"
    case accountLocked = "Account Locked"
    case unknownError = "Unknown error"
}

And lastly my call to a login web service :

func sessionCall(_ res: Result<LoginResponseData?, Error>) {
        switch res {
        case .success(let response):
                ...... // Some code
        case .failure(let error):
                self.showLoginError(error: //HOW TO GET THE STRING FROM ERROR HERE)
        }
    }

Thing is I want to get the string representing my enum in order to show the proper error message, but I can access this value at all. If I try with localizedDescription of the error I get a totally different string which has this content: "The operation could not be completed".

Matias Barrios
  • 4,674
  • 3
  • 22
  • 49

1 Answers1

3

If you want to use localizedDescription to get error messages from all the errors including yours, your custom error types need to conform to LocalizedError.

Please try this:

enum LoginErrors: String, LocalizedError {
    case uOrPincorrect = "The username or password you entered is/are wrong"
    case accountLocked = "Account Locked"
    case unknownError = "Unknown error"

    var errorDescription: String? {
        self.rawValue
    }
}
OOPer
  • 47,149
  • 6
  • 107
  • 142