Juan Rangel
Juan Rangel

Reputation: 1793

If Decoder Fails Use Other Decoder

I am creating an application that communicates with a web app using Laravel as the backend. I am trying to handle form validation but running into an issue.

For example, let's say when a user logs in.

I am attempting to login using a URLRequest.

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
    guard let data = data, error == nil else {return}
}
task.resume()

I've created two Structs

struct LoginRequest: Decodable {
    let access_token: String
}

And

struct LoginErrors: Decodable {
    let error: String
    let message: String
}

Now I am decoding the json response with this

do {
     let login = try JSONDecoder().decode(LoginRequest.self, from: data!)
} catch {
    // error
}

How can I attempt to decode the LoginErrors struct when the LoginRequest fails? If this is bad practice, what is the best way to parse the json that has the errors?

Here is an example of the json I need to handle.

{
    "token_type": "Bearer",
    "expires_in": 12345678,
    "access_token": "abc123",
    "refresh_token": "abc123"
}
// Error JSON
{
    "error": "invalid_credentials",
    "message": "The user credentials were incorrect."
}

Upvotes: 1

Views: 49

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100523

You can try

do {
   let login = try JSONDecoder().decode(LoginRequest.self, from: data!)
} catch {
   let error = try? JSONDecoder().decode(LoginErrors.self, from: data!)
}

despite this isn't a best practice you need to handle that from your server to change the returned status code and act accordingly

Upvotes: 1

Related Questions