Error Handling: Silent Bullets

Error Handling: Silent Bullets

ยท

2 min read

Hello there! ๐Ÿ‘‹

Itโ€™s been a while, and I really missed writing a blog early in the morning! Now that I have some sort of free time, I wanted to discuss some techniques in Error handling over the coming days that I learned, and well, thought it would be interesting to share! ๐Ÿ˜„

I wanted to start with something that may not be obvious all the time, especially when you prefer to be safe away from crashes, which is unwrapping optional variables

The Problem ๐Ÿ’ฅ

func handle(deeplink: String) {
  guard let deeplinkUrl = URL(string: deeplink) else { return }
  ...
}

In the current context of the above method, you need to make sure that the URL is unwrapped after receiving the deeplink, and if the deeplink is invalid for whatever reason, we wonโ€™t continue executing the method

Seemsโ€ฆ kinda normal, right?

Nope, itโ€™s not always okay to early return silently, while it may not affect the programโ€™s execution or create any bug (not always)โ€ฆ It may be a sign of something went wrong, without firing any alarms, like a bug hiding in plain sight, like a...

Silent Bullet ๐Ÿ”ซ

Silent Bullets are parts of your code that fail without firing any warnings, and the pattern where you unwrap a variable without handling the case where its indeed nil may create weird behaviors, and we, the developers, should be notified when something like this goes wrong

Remedy ๐ŸŒฟ

Logging such behavior should be what you do in such case, to give you a second pair of eyes when something goes wrong, be it a technical issue, bad usage from another team, or a glitch in the matrix

Cat walking in Matrix

For the scope of this post, we will stop at just printing this issue, in the next post we will talk more about Logs and why you need them, then walk you through a better approach than just printing it

func handle(deeplink: String) {
  guard let deeplinkUrl = URL(string: deeplink) else { 
    debugPrint("coudln't unwrap \(deeplink) as a URL for handling it.")
    return
  }
  ...
}

Conclusion

Not always unwrapping optional parameters may be a good thing, when reviewing/writing unwrapping code, ask yourself, is it normal for my use case that this variable may become nil by design? Or if it became nil that indicates a problem? ๐Ÿค”

Happy Coding!

ย