Exceptions are a great tool to handle unforeseen situations and system states. Although you might nod your head and tell yourself: "Yes Alex I know. What do you want to tell me?"
It's about so much code that I have seen, that's lacking usage of exceptions.
function validate() {
const {email, password} = form.values; // for example
if (email.length == 0) {
alert("Email has to be provided");
return;
}
if (email.indexOf('@') === -1) {
alert("The provided email is invalid");
return;
}
if (password.length === 0) {
alert("No password provided");
return;
}
}
This looks ugly and I think we all agree on this. But why does it come back over and over again?
I think it's the fear of using exceptions. They are perfectly designed to achieve invalid states in a system. So why not use it for form validation?
A simple validation function allows us to write the requirements in a declarative way. It will throw an exception if the requirement isn't met.
function validate(cond, errorMsg) {
if (!cond) throw new Error(errorMsg);
}
We can now reuse this one line of code to define multiple requirements line by line. Result? Our code becomes much more clear!
Let's take a look at the login form. We will write a method just with our validation rules.
const validateLoginForm = (formValues) => {
validate(formValues.email.length > 0, "No email provided");
validate(formValues.email.indexOf('@') == -1, "Provided email is not valid");
validate(formValues.password.length > 0, "No password provided");
}
After everything is set up, we can catch validation exceptions once the user presses the button and signIn
is called.
In the catch block, we open an alert with the message of the error.
const signIn = (formValues) => {
try {
validateLoginForm(formValues);
} catch(error) {
alert(error);
return;
}
}
The best reason, you might miss out now
Let's say you want to modularize your application. There is one module for form validation and another for delivering the results to a ReST API, another to a terminal UI.
Sticking to the first approach will leave you with a huge mess and tightly coupled dependencies to the dom (alert).
If you use exceptions, however, then you can handle those exceptions differently in different modules, apps and platforms.
On top of that, you can dig into the stack trace for debugging and provide further information, by changing one line. Not hundreds and thousands.
Conclusion
Don't be afraid of using exceptions. They are great and the right way for conveying information about invalid system states.
If this post took your fear or taught you something new, show it with a heart.