I am using the library google-libphonenumber
and noticing that if a non viable option is passed to phoneUtil.parseAndKeepRawInput('202-341-2345', 'ZZ')
it automatically throws and errors and breaks the site.
What I want to do is either allow some way of saying if this piece of code did not work then alert and error or I need a way to validate the input with all the i18n iso codes before.
So the exact problem that I was trying to solve was to not crash the application because an invalid country calling code or iso code was passed in. If for example I passed zz into the second argument of:
phoneUtil.parseAndKeepRawInput('202-341-2345', 'ZZ')
This was causing my whole application to crash and show the error. While all I wanted to do is only alert the error and not let the user continue with the process. So there was two ways to do this. Either validate the country calling code or iso code, or do a try catch block to alert an error if the variable did not work.
I took the try catch block since this is a way I can show the error directly which tells the user their iso code is wrong anyway. So no need for validating either since it is already done.
Here is the code:
let userNumber = null;
try {
userNumber = phoneUtil.parseAndKeepRawInput(
this.state.phoneNumber,
this.state.isoCode.toUpperCase()
);
} catch (e) {
alert(e);
return;
}
if (userNumber) {
alert(phoneUtil.isValidNumber(userNumber));
alert(phoneUtil.format(userNumber, PNF.E164));
return;
}