"undefined" in exception handling while printing custom error message - javascript

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?

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

javascript error handling doesn't work

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

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.

IE - "Error: Object doesn't support this action"

I'm getting a frustrating javascript error in IE7 that I can't get around. It is working fine in Chrome and Firefox, but not in IE..
The line I am getting the error in is: item = listGetAt(list,'1','-');
This is calling the following custom method:
function listGetAt(list,position,delimiter) {
if(delimiter == null) { delimiter = '-'; }
list = list.split(delimiter);
if(list.length > position) {
return list[position];
} else {
return list.length;
}
}
Can anyone see something I can't?
Many thanks in advance for any help.
Jason
Poor code
Why pass a string as a numeric parameter?
I would consider
function listGetAt(list,position,delimiter) {
delimiter = delimiter || '-';
if (list.indexOf(delimiter) ==-1) return -1;
list = list.split(delimiter);
return list.length>=position?list[position]:null;
}

Understanding try..catch in Javascript

I have this try and catch problem. I am trying to redirect to a different page. But sometimes it does and some times it doesnt. I think the problem is in try and catch . can someone help me understand this. Thanks
var pg = new Object();
var da = document.all;
var wo = window.opener;
pg.changeHideReasonID = function(){
if(pg.hideReasonID.value == 0 && pg.hideReasonID.selectedIndex > 0){
pg.otherReason.style.backgroundColor = "ffffff";
pg.otherReason.disabled = 0;
pg.otherReason.focus();
} else {
pg.otherReason.style.backgroundColor = "f5f5f5";
pg.otherReason.disabled = 1;
}
}
pg.exit = function(pid){
try {
if(window.opener.hideRecordReload){
window.opener.hideRecordReload(pg.recordID, pg.recordTypeID);
} else {
window.opener.pg.hideRecord(pg.recordID, pg.recordTypeID);
}
} catch(e) {}
try {
window.opener.pg.hideEncounter(pg.recordID);
} catch(e) {}
try {
window.opener.pg.hideRecordResponse(pg.hideReasonID.value == 0 ? pg.otherReason.value : pg.hideReasonID.options[pg.hideReasonID.selectedIndex].text);
} catch(e) {}
try {
window.opener.pg.hideRecord_Response(pg.recordID, pg.recordTypeID);
} catch(e) {}
try {
window.opener.pg.hideRecord_Response(pg.recordID, pg.recordTypeID);
} catch(e) {}
try {
window.opener.window.parent.frames[1].pg.loadQualityMeasureRequest();
} catch(e) {}
try {
window.opener.pg.closeWindow();
} catch(e) {}
parent.loadCenter2({reportName:'redirectedpage',patientID:pid});
parent.$.fancybox.close();
}
pg.hideRecord = function(){
var pid = this.pid;
pg.otherReason.value = pg.otherReason.value.trim();
if(pg.hideReasonID.selectedIndex == 0){
alert("You have not indicated your reason for hiding this record.");
pg.hideReasonID.focus();
} else if(pg.hideReasonID.value == 0 && pg.hideReasonID.selectedIndex > 0 && pg.otherReason.value.length < 2){
alert("You have indicated that you wish to enter a reason\nnot on the list, but you have not entered a reason.");
pg.otherReason.focus();
} else {
pg.workin(1);
var n = new Object();
n.noheaders = 1;
n.recordID = pg.recordID;
n.recordType = pg.recordType;
n.recordTypeID = pg.recordTypeID;
n.encounterID = request.encounterID;
n.hideReasonID = pg.hideReasonID.value;
n.hideReason = pg.hideReasonID.value == 0 ? pg.otherReason.value : pg.hideReasonID.options[pg.hideReasonID.selectedIndex].text;
Connect.Ajax.Post("/emr/hideRecord/act_hideRecord.php", n, pg.exit(pid));
}
}
pg.init = function(){
pg.blocker = da.blocker;
pg.hourglass = da.hourglass;
pg.content = da.pageContent;
pg.recordType = da.recordType.value;
pg.recordID = parseInt(da.recordID.value);
pg.recordTypeID = parseInt(da.recordTypeID.value);
pg.information = da.information;
pg.hideReasonID = da.hideReasonID;
pg.hideReasonID.onchange = pg.changeHideReasonID;
pg.hideReasonID.tabIndex = 1;
pg.otherReason = da.otherReason;
pg.otherReason.tabIndex = 2;
pg.otherReason.onblur = function(){
this.value = this.value.trim();
}
pg.otherReason.onfocus = function(){
this.select();
}
pg.btnCancel = da.btnCancel;
pg.btnCancel.tabIndex = 4;
pg.btnCancel.title = "Close this window";
pg.btnCancel.onclick = function(){
//window.close();
parent.$.fancybox.close();
}
pg.btnHide = da.btnHide;
pg.btnHide.tabIndex = 3;
pg.btnHide.onclick = pg.hideRecord;
pg.btnHide.title = "Hide " + pg.recordType.toLowerCase() + " record";
document.body.onselectstart = function(){
if(event.srcElement.tagName.search(/INPUT|TEXT/i)){
return false;
}
}
pg.workin(0);
}
pg.workin = function(){
var n = arguments.length ? arguments[0] : 1;
pg.content.disabled = pg.hideReasonID.disabled = n;
pg.blocker.style.display = pg.hourglass.style.display = n ? "block" : "none";
if(n){
pg.otherReason.disabled = 1;
pg.otherReason.style.backgroundColor = "f5f5f5";
} else {
pg.otherReason.disabled = !(pg.hideReasonID.value == 0 && pg.hideReasonID.selectedIndex > 0);
pg.otherReason.style.backgroundColor = pg.otherReason.disabled ? "f5f5f5" : "ffffff";
pg.hideReasonID.focus();
}
}
I think your main problem is that you're swallowing exceptions, which is very bad. This is why "it works sometimes". Something is throwing an exception, and you're catching it, but then you're not doing anything else after that. At the very least I would display some sort of error message in your catch block.
A few other problems:
Are you sure you need those multiple try..catch blocks? The current assumption in your code is that each line that is wrapped in a try..catch is independent of the others, and execution can still proceed if something goes wrong in any one (or more) of those statements. Are you sure this is what you want? If so, there is definitely a better way of handling this.
If the statements are not independent of each other, and if a failure at any point means that execution cannot proceed, then you can wrap all of those statements in a single try..catch block and display an error message in the catch
Like I said before, swallowing exceptions is very bad! You're hiding the problem and not achieving anything. It also makes debugging extremely hard, because things will stop working and you will have no idea why (no exception, no logging, no error messages). Exceptions are used when something unexpected happens that interrupts normal program flow. It is something you definitely want to handle.
I think what you want can be done this way:
try {
if(window.opener.hideRecordReload){
window.opener.hideRecordReload(pg.recordID, pg.recordTypeID);
} else {
window.opener.pg.hideRecord(pg.recordID, pg.recordTypeID);
}
window.opener.pg.hideEncounter(pg.recordID);
window.opener.pg.hideRecordResponse(pg.hideReasonID.value == 0 ? pg.otherReason.value : pg.hideReasonID.options[pg.hideReasonID.selectedIndex].text);
window.opener.pg.hideRecord_Response(pg.recordID, pg.recordTypeID);
window.opener.pg.hideRecord_Response(pg.recordID, pg.recordTypeID);
window.opener.window.parent.frames[1].pg.loadQualityMeasureRequest();
window.opener.pg.closeWindow();
}
catch(e) {
console.log(e);
}
This way, if an exception occurs anywhere along those series of statements, the catch block will handle it.
Javascript also doesn't have true checked-exceptions. You can get around it by having a single try block, and inspecting the exception object that you receive*.
Expanding on what I talked about earlier, there are two ways of handling exceptions. The first way, like I showed earlier, assumes that when an exception happens, the code is in an invalid/undefined state and this therefore means that the code encountered an unrecoverable error. Another way of handling exceptions is if you know it is something you can recover from. You can do this with a flag. So:
try {
doSomething();
}
catch(e) {
error = true;
}
if(error) {
doStuffToRecoverFromError();
}
else {
doOtherStuff();
}
In this case the flow of your logic depends on an exception being thrown. The important thing is that the exception is recoverable, and depending on whether it was thrown or not, you do different things.
*Here is a somewhat contrived example that demonstrates checked-exceptions. I have two exceptions called VeryBadException and ReallyBadException that can be thrown (randomly) from two functions. The catch block handles the exception and figures out what type of exception it is by using the instanceof operator):
function VeryBadException(message) {
this.message = message;
}
function ReallyBadException(message) {
this.message = message;
}
function foo() {
var r = Math.floor(Math.random() * 4);
if(r == 2) {
throw new VeryBadException("Something very bad happened!");
}
}
function bar() {
var r = Math.floor(Math.random() * 4);
if(r == 1) {
throw new ReallyBadException("Something REALLY bad happened!");
}
}
try {
foo();
bar();
}
catch(e) {
if(e instanceof VeryBadException) {
console.log(e.message);
}
else if(e instanceof ReallyBadException) {
console.log(e.message);
}
}
It's good practice do something with the caught exceptions.
What's happening here is that if there's an error (say loading a page fails) an exception is thrown inside one of your try blocks. The corresponding catch block grabs it and says "that exception has been dealt with" but in actuality you've not done anything with it.
Try putting a print(e.Message); inside your catch blocks to find out exactly what error is causing the page not to load and then add code to your catch block to deal with this error.

Categories

Resources