javascript error handling doesn't work - javascript

I'm just trying to read from a textbox and check if the textbox contains only letters. But when i try to catch the error. nothing happens. the alert message works fine which means the if statement is executed correctly but the problem with the error handling. what am I doing wrong?
function validateSearchInput() {
let searchBoxValue = document.getElementById('search-box').value
let lettersOnlyPattern = (/^[a-zA-Z ]+$/);
try {
if (!lettersOnlyPattern.test(searchBoxValue)) {
alert('this will pop-up');
throw new Error('Please enter letters only');
}
location.href = "country.html";
} catch (e) {
console.log(e.message);
}
}
thanks all

Related

How to make website errors display without console errors?

I am making a text changer website https://textchanger.netlify.com/ and ran into a problem when trying to have a error display. I want the error to be displayed whenever the user tries to convert "nothing".
The error does display, and everything to that aspect works fine, but there's some errors in the Chrome console I can't seem to debug.
Error: textchanger.js:43 Uncaught TypeError: Cannot read property 'split' of undefined
at Scrambler (textchanger.js:43)
at HTMLButtonElement.<anonymous> (textchanger.js:80)
If anybody has ideas that'd be awesome!
JSfiddle: https://jsfiddle.net/MysteriousDuck/duc0atjz/
//Check if textinput is not empty
function fooBar(text) {
if (document.getElementById("inputText").value == "") {
console.log('Can not convert nothing!')
} else {
capitalizer()
}
}
return textArray.join(''); {
}
//Capitalize every odd letter
function capitalizer() {
if (document.getElementById("inputText").value == "") {
alertify.error('Can not convert nothing!')
} else {
var x = document.getElementById("inputText").value;
var string = "";
for (let i = 0; i < x.length; i++) {
if (i % 2 == 0) {
string = string + x[i].toUpperCase();
} else {
string = string + x[i];
}
}
return string;
}
}
The error is contained within your scrambler() function. This function is being executed every time a user clicks the Convert button irregardless of the input they entered into the textarea. This because your event listener is simply listening to clicks on this Convert button and for each click it simply runs the scrambler() function based on said input. You need to add input validation check here to fix this from only running on valid input.
Your Convert Button Listerner:
convertText.addEventListener('click', function() {
if (checkbox_1.checked && checkbox_2.checked) {
console.log("Capitalizing + Scrambling text");
document.getElementById("convertedText").value = scrambler(capitalizer());
} else if (checkbox_2.checked) {
console.log("Scrambling text");
var text = document.getElementById("inputText").value;
document.getElementById("convertedText").value = scrambler(text);
} else if (checkbox_1.checked) {
console.log("Capitalizing text");
document.getElementById("convertedText").value = capitalizer();
}
})
Notice there is no input validation in this event listener and it assumes a valid value within your convertedText textarea so this is why you're getting the undefined error when a user enters nothing to be converted i.e. there is no convertedText to split
Uncaught TypeError: Cannot read property 'split' of undefined
Hopefully that helps!
The code document.getElementById("convertedText").value = scrambler(capitalizer()); throws an error.
capitalizer() in the code upper returns undefined
Because inside the method fulfills the condition alertify.error('Can not convert nothing!') which returns nothing i.e undefined
Then scrambler tries to split a text parameter which equal undefined

"undefined" in exception handling while printing custom error message

Hi I am getting a "undefined" with my custom error message.Why? I only want error message.Can anyone help please.
function divide() {
let num = 2;
let den = 0;
try{
if (den == 0){
throw new Error("division invalid");
}
return Number(num/den);
} catch(e){
console.log(e.message);
}
}
console.log(divide());
Functions that don't have an explicit return, return undefined implicitly. You are throwing an error and then not returning anything in the catch block. Since you aren't returning a value, it sends undefined.
function divide() {
let num = 2;
let den = 0;
try {
if (den == 0) {
throw new Error("division invalid");
}
return Number(num/den);
} catch(e){
console.log(e.message);
return 'Can\'t divide by 0!';
}
}
console.log(divide());
Notice in this code snippet that I am returning a string in the catch. The line return Number(num/den); is never called because there was an error.
Instead of logging the error within the function, you can return it to the calling method.
function divide() {
let num = 2;
let den = 0;
try {
if (den == 0) {
throw new Error("division invalid");
}
return Number(num / den);
} catch (e) {
return e.message;
}
}
console.log(divide());
your code is working absolutely correct . I have tested this on my console.
Most probably the problem is with your console settings, currently the console must be set to show errors only. So , change the chrome console output to Verbose or All. I am attaching the snapshot of how to change the settings and the output of your code as per your expectation.
Solution to your problem Click here
For completeness: In the current version of chrome, the setting is no longer at the bottom but can be found when clicking the "Filter" icon at the top of the console tab (second icon from the left)
You can click here for further reference.
I hope this solves your problem . Thanks :)
Console.log() function returns undefined. So do what #Krypton suggests, though that will still lead to the undefined still showing up. But hey, at least it's one less undefined, no?

JavaScript Try Catch

I'm looking at some code on a website that hides / shows content on a click.
function expando() {
try {
if (document.getElementsByClassName) {
var e = document.getElementsByClassName("expandlink");
t = 0;
} else {
var e = document.querySelectorAll(".expandlink"),
t = 1;
};
if (null != e) {
for (var a = 0; a < e.length; ++a) e[a].onclick = function() {
return OpenClose(this), !1
};
if (1 == t)
for (var a = 0; a < e.length; ++a) {
var n = e[a].href,
r = n.indexOf("#"),
i = n.substr(r + 1),
l = document.getElementById(i);
l.className = l.className + " expandtargetIE8"
}
}
} catch (o) {}
}
function OpenClose(e) {
try {
var t = e.href,
a = t.indexOf("#"),
n = t.substr(a + 1),
r = document.getElementById(n);
r.className = "expandtarget" === r.className ||
"expandtarget expandtargetIE8" === r.className ?
"expandtargeted" : "expandtarget expandtargetIE8",
e.className = "expandlink" === e.className ?
"expandlink expandlinked" : "expandlink"
} catch (i) {}
}
window.onload = function() {
expando()
};
Here is the JS Fiddle.
https://jsfiddle.net/amykirst/3hbxwv1d/
I've never seen the JavaScript try...catch statement. I looked at some tutorials, and they all say that they are for error testing. Why would it be used here?
It doesn't look like the catch actually does anything.
Note: this code had been minified. I used an online tool to unminify it.
The try..catch block here is used for error handling. It's used here to allow the code to continue normal execution if an error does arise.
Not all browsers will support both document.getElementsByClassName and document.querySelectorAll. On a browser which doesn't support either, we'd get the following error:
Uncaught TypeError: document.querySelectorAll is not a function
...and further code execution would stop.
However with a try..catch block here, the code instead wouldn't alert us about the error at all (at least, not without inspecting o within the catch block). Execution would continue as normal. It's no longer an uncaught error, it's a caught error which simply has nothing done with it.
If in the same browser we're to adjust the above code to log o within the catch block:
... } catch (o) { console.log(o) }
The same message shown above would be displayed on the console, without the "uncaught" part:
TypeError: document.querySelectorAll is not a function(…)
Actually there are few real use case of try-catch.
Error handling : Your JS function/statements may throw error, like TypeError (Accessing undefined,null) , JsonParseError etc. Sometimes you need that to be handled, so that next set of statements has to be executed. If it is not handled, the JS engine will throw it and halts the function execution.
Getting meaningfull information from multiple function call stack: You may get into situation, in legacy codes, that function f1 is calling f2 and f2 calling f3 and so on. You may want to do some validation check and if validation fails you may like to stop the flow and show meaningfull error message. (like saying, invalid state). To handle this kind of scenario, we can handle with Custom Exception.
function ValidationError(message) {
this.name = "IocError";
this.message = (message || "Validation/System Error");
}
ValidationError.prototype = Error.prototype;
we can throw the custom error, if we see any validation error, like throw new ValidationError('Rule is missing...') in the function f3.
try {
...
} catch(e) {
if(e instanceof ValidationError) {
infoBox(e.message);
return false;
} else {
//This is not validation error, some other unknown issue has occurred
throw e;
}
}
We will use the above block to catch the exception in function f1 and if it is of type ValidationError, we'll display proper error message. If it as any other type we'll throw back for future debug purpose.

Returning true or false from javascript function

I'm doing a regex check on a string within a function:
function ValidateZipCodeString(listOfZipCodes) {
var regex = /^([, ]*\d{5})+[, ]*$/,
matches = regex.exec(listOfZipCodes);
if (regex.exec(listOfZipCodes) === null) {
console.log('validation failed');
return false;
} else {
console.log('validation passed');
return true;
}
}
The regex is correctly detecting a valid/invalid list of zip codes.
I'm calling the function with this:
console.log('zip code: ' + listOfZipCodes);
if (ValidateZipCodeString(listOfZipCodes)) {
$tr.find('label#lblCoverageEditError').text('There is invalid text in the list of zip codes. Only 5-digit zip codes allowed.').show();
} else {
console.log('validate function returned true');
}
The problem is that the above if/else goes to the else clause, when the console output within the validation function shows "validation failed". So I must not be calling that function right.
What's the correct way to do what I'm trying to do?
Your function could be greatly simplified to:
function ValidateZipCodeString(listOfZipCodes) {
var regex = /^([, ]*\d{5})+[, ]*$/;
if (regex.test(listOfZipCodes)) {
console.log('validation passed');
return true;
} else {
console.log('validation failed');
return false;
}
}
...or:
function ValidateZipCodeString(listOfZipCodes) {
var regex = /^([, ]*\d{5})+[, ]*$/;
return regex.test(listOfZipCodes);
}
...or even just:
function ValidateZipCodeString(listOfZipCodes) {
return /^([, ]*\d{5})+[, ]*$/.test(listOfZipCodes);
}
...but the real issue (as Teemu points out) is not in your function, but in the use of it. Your function answers the question, "Is this a valid zip code string?", but your use of it is saying, "Say this is invalid if my function says it is."
Actually your validation function doesn't return true when validation fails. You just check the value incorrectly, it should be:
if (!ValidateZipCodeString(listOfZipCodes)) {
$tr.find('label#lblCoverageEditError').text('There is invalid text in the list of zip codes. Only 5-digit zip codes allowed.').show();
} else {
console.log('validate function returned true');
}
Others correctly pointed out that you just had your tests in the wrong order. However, and more importantly, your regex is incorrect, as it will for example return true for "1234567890".
Here is a suggestion:
function ValidateZipCodeString(listOfZipCodes) {
return /^\d{5}(\s*,\s*\d{5})*$/.test(listOfZipCodes);
}

Javascript: onSubmit function submits form before function has finished?

I'm asking this because I am at a complete loss myself and need a fresh pair of eyes.
The following JavaScript function is successfully called on submission of the connected HTML form. The function starts and the first two if statements run (and halt the submission if they return false).
Then, the first test alert "before" appears and then the form submits, completely missing out the rest of the function. While testing I changed the final line to return false so that whatever happen the function should return false, but the form still submitted.
function validateForm(form)
{
// declare variables linked to the form
var _isbn = auto.isbn.value;
var _idisplay = auto.isbn.title;
var _iref = "1234567890X";
// call empty string function
if (EmptyString(_isbn,_idisplay)==false) return false;
// call check against reference function
if (AgainstRef(_isbn,_iref,_idisplay)==false) return false;
// call check length function
alert("before");///test alert
////// FORM SUBMITS HERE?!? /////////////
if (AutoLength(_isbn)==false) return false;
alert("after");///test alert
// if all conditions have been met allow the form to be submitted
return true;
}
Edit: this is what AutoLength looks like:
function AutoLength(_isbn) {
if (_isbn.length == 13) {
return true; {
else {
if (_isbn.length == 10) {
return true; {
else {
alert("You have not entered a valid ISBN10 or ISBN13. Please correct and try again.");
return false;
}
}
There are errors in your implementation of AutoLength. Currently, it looks like this:
function AutoLength(_isbn) {
if (_isbn.length == 13) {
return true; { // <------ incorrect brace
else {
if (_isbn.length == 10) {
return true; { // <------ incorrect brace
else {
alert("You have not entered a valid ISBN10 or ISBN13. Please correct and try again.");
return false;
}
}
See how it doesn't close all of its blocks? That's because you've used the wrong brace in two places, and you've forgotten to close the function.
You could rewrite the function like this:
function AutoLength(_isbn) {
return _isbn.length === 13 || _isbn.length === 10;
}
If you're hell-bent on using alert, you can do that inside validateForm (although I would try to find a more user-friendly way to show the error message).
In the future, when you're trying to debug code, you can use try and catch to "catch" Errors as they happen, like this:
try {
if (false === AutoLength(_isbn)) {
return false;
}
} catch (e) {
alert('AutoLength threw an error: '+e.message);
}
If the execution of the function is terminated by a runtime error, the form submits. So check out the script console log for error messages.

Categories

Resources