Skip to content
This repository has been archived by the owner on Jun 18, 2019. It is now read-only.

Log warnings when invalid elements are found in a collection #189

Open
wants to merge 4 commits into
base: master
Choose a base branch
from

Conversation

jakunico
Copy link

@jakunico jakunico commented Jun 6, 2017

Hey! We wanted to share a little feature we included in our project that you guys might also like.

Motivation

We have a feature in our app that is a list of trips. Some users were reporting that some trips were missing from it. We started researching and found out that the problem was in unboxing an entity of that list.

When unboxing of an entity fails, we always log an error into our non-fatal log and send it to our API. In this case, we didn't have any error about this.

Upon further research, we found that the issue was that the array was using allowInvalidElements property so that one item doesn't break the unbox of that collection. In this case, one trip was broken and thus it was not listed.

We use allowInvalidElements in multiple places in our app. We want to ensure that whenever an element in a list fails, we're informed about it and that's why we implemented this feature.

How it works

There's a global logger for all warnings in Unboxer.warningLogger. Devs who are using Unbox in their project can optionally set a logger in this property to start listening to these notifications.

Internally we added a few calls to this static property from inside the collection mapping methods.

Further improvement

We identified other types of warnings that we are interested in logging. Imagine you have the following model:

struct User: Unboxable {
    let name: String
    let profession: Profession? 
}

struct Profession: Unboxable {
   let name: String
}

Now, imagine the API sends you the following:

{ 
"name": "Nicolas",
"profession": "Engineer"
}

When unboxing that JSON, you'll get the following:

let data = /*json data*/
let user: User = try unbox(data: data)
print(user.name) // "Nicolas"
print(user.profession) // nil

So in this example the API is sending a profession attribute but we're not correctly parsing it. As it is an optional value, unbox process succeeds correctly but something is wrong.

This could be also logged as a warning to indicate that the key was present but unboxing failed.

@Caioflandau
Copy link

Can we get this merged? This would be extremely helpful and the code seems OK for me, but I'm not very knowledgable about Unbox internals

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants