2019-02-22-try-catch-exception-rather-than-return-codes
Last updated
Was this helpful?
Last updated
Was this helpful?
In a few weeks ago, I rarely used try-catch
. But after I read again, I realised something and used try-catch more frequently.
Let's consider a scenario: a program has an user's information screen with usename, avatar field. After user changed [username, avatar], then press UPDATE button. The program will do:
Validate username (longer than 5 characters).
Show loading animation
Upload avatar to an image server.
Update user's info: username, avatar.
Show Success alert, hide loading animation, .
Hide loading animation if fail at any point.
Go with these codes (just focus on validateUsername
and onUpdateButtonPressed
function):
We can smell something in the onUpdateButtonPressed
function:
2 return
lines(better than nested if)
chaining Promises(better than nested Promises)
a little complex show/hide loading flow
hard to figure out the updating flow
It's not bad at all. But imagine, if we have more error codes and chaining Promises, the code will be massive and hard to be maintained.
So let's refactor onUpdateButtonPressed
with try-catch
and async/await
What I did:
In validateUsername
, instead of return error codes, throw
them.
In onUpdateButtonPressed
, instead of using then/catch
with Promises, using try-catch
and async/await
.
I think the code is good now:
We can easy understand the flow line by line: validateUsername -> showLoading -> uploadImages -> updateUserInfo -> showSuccessAlert
Errors are handled in one place handleError
.
From now, I always try to use try-catch-finally
first for cases as this scenario.
HAPPY CODING!
More detail about