Firefox not catching "undefined" error in javascript - javascript

I have some javascript code which calls a servlet with parameters based on the selected option from a SELECT list. It is possible that there will be no options in the selectCampaigns(account) so there is a try and catch.
The code in the catch should be called if,
var selectedCampaign = selectCampaigns.options[selectCampaigns.selectedIndex].text;
fails. This works in both chrome and IE but in firefox it gives a TypeErrror,
TypeError: selectCampaigns.options[selectCampaigns.selectedIndex] is undefined
which does not trigger the catch. May I have some suggestions on how to handle this? (in addition firefox does not show any of the alerts that I have inserted for debugging).
function selectcampaign(account) {
alert('alert1');
var selectCampaigns = document.getElementById("campaignSelect");
var urlstrg = "http://localhost:8080/SalesPoliticalMapping/OrgChart";
try {
var selectedCampaign = selectCampaigns.options[selectCampaigns.selectedIndex].text;
urlstrg = "http://localhost:8080/SalesPoliticalMapping/OrgChart?account=" + account + "&campaign=" + selectedCampaign;
} catch(err) {
alert(err);
urlstrg = "http://localhost:8080/SalesPoliticalMapping/OrgChart?account=" + account;
} finally {
window.location.href = urlstrg;
}
};

You should better test the value instead of dealing with errors.
function selectcampaign(account) {
var selectCampaigns = document.getElementById("campaignSelect");
var urlstrg = "http://localhost:8080/SalesPoliticalMapping/OrgChart?account=" + account;
if(selectCampaigns.options[selectCampaigns.selectedIndex]) {
urlstrg += "&campaign=" + selectCampaigns.options[selectCampaigns.selectedIndex].text;
}
window.location.href = urlstrg;
};

Related

In the function below, IE says that ')' is missing:

same code working in chrome and edge, but not working in ie
function PostAVWorkspaceTab(ParamURL, title = "") {
var DecodedURL = decodeURL(ParamURL);
const queryStringTitleValue = getQueryStringValueByKey(DecodedURL, 'Title');
var jsonData = {};
jsonData["MessageId"] = 1;
jsonData["Title"] = queryStringTitleValue ? queryStringTitleValue : title;
jsonData["URL"] = DecodedURL;
jsonData["ObjectId"] = 0;
try {
window.parent.postMessage(JSON.stringify(jsonData), "http://localhost:9002/TokenInfo");
}
catch (e) { }
console.log("PostAVWorkspaceTab(4): send message to open tab with URL = [" + DecodedURL + "] - " + "http://localhost:9002/TokenInfo" + jsonData);
}
Problem is in line PostAVWorkspaceTab(ParamURL, title = "") - to be specific the second parameter - title.
IE doesn't support default value in the parameter. Try this:
PostAVWorkspaceTab(ParamURL, title) {
if (title === undefined){
title = "";
}
....
}
As already informed by other community members, the IE browser do not support default parameters.
Reference:
Default parameters
This is the reason that you are getting an error in the IE browser.
To fix the issue you can try to remove the default value for the parameter and only try to pass the parameter will fix the issue.
You can try to implement any other logic like passing the empty value and check if the value is empty then try to use default value from the variable in function.

Invalid-key request passed to a map to retrieve the value. Handle this exception

I have a map, and am trying to retrieve a value based on the key passed in the form of "id". However in some cases, the "id" that is passed is invalid i.e. it is not present in the Map, which in turn makes the application crash. Is throwing the Error causing this issue ? I tried experimenting with the try-catch but it still continued to malfunction i.e. the screen stops loading on detecting this error. Not sure if I wrote the try-catch correctly. how do I best handle this to stop the application from malfunctioning in such a case and continue loading the screen.
Failed approach:
this.hmItems = {}; //Map<Integer,Item>
Address.prototype.getItem = function (id) {
var item = this.hmItems[id];
if (!item)
throw new Error("'Illegal argument: id=" + id);
return item;
};
Another failed approach:
this.hmItems = {}; //Map<Integer,Item>
Address.prototype.getItem = function (id) {
try {
var item = this.hmItems[id];
if (!item) throw "illegal id!!!!!!!!!";
return item;
} catch(err) {
//log exception
}
}
Use hasOwnProperty to see if the property exists on the hmItems object:
this.hmItems = {}; //Map<Integer,Item>
Address.prototype.getItem = function(id) {
if (!this.hmItems.hasOwnProperty(id)) {
throw new Error("'Illegal argument: id=" + id);
}
return this.hmItems[id];
};
Just checking var item = this.hmItems[id]; if (!item) isn't a good test because it'll fail even if the property exists on the object but is falsey, like 0 or null.
Live demo:
class Address {
hmItems = {
1: 10,
2: 0
};
getItem(id) {
if (!this.hmItems.hasOwnProperty(id)) {
throw new Error("'Illegal argument: id=" + id);
}
return this.hmItems[id];
}
}
const a = new Address();
// Works:
console.log(a.getItem(1));
// Works:
console.log(a.getItem(2));
// Throws:
try {
console.log(a.getItem(3));
} catch(e) {
console.log(e.message);
}

Getting Compile error in Microsoft JScript (expected)

I tested a code with my friend and the code worked and now I wanted to test this again and got a Compile error in Microsoft JScript
Everything worked before
var iTest = 0;
if (iTest) {
let sText = "This is a template string which can contain variables like ${iTest}";
console.log(sText);
} else if (!iTest) {
let fnc = (iRadius, iPi = 3.14) => {
console.log("The area of the circle with the radius ${iRadius}cm is ${Math.round(iPi * iRadius * iRadius)}cm²");
}
fnc(3.14);
} else {
/* This is never going to be called since else if is already handling the only option besides the if */
}
var fnc = (iAlpha, iBravo, cb) => {
cb(iAlpha + iBravo);
}
fnc(84,255,(iResult) => {
console.log(iResult);
});
Template literals and arrow functions are not available in JScript. The latest version of JScript is based on ES5, and those two features are only available in ES2015. And console is not available in JScript if you are using the Windows Script Host; instead, use WScript.Echo().
var iTest = 0;
if (iTest) {
var sText = "This is a template string which can contain variables like " + iTest;
WScript.Echo(sText);
} else {
var fnc = function(iRadius, iPi) {
iPi = 3.14;
WScript.Echo("The area of the circle with the radius " + iRadius + "cm is " + Math.round(iPi * iRadius * iRadius) + "cm²");
}
fnc(3.14);
}
var fnc = function(iAlpha, iBravo, cb) {
cb(iAlpha + iBravo);
}
fnc(84, 255, function(iResult) {
WScript.Echo(iResult);
});
It would also be nice if you could provide more information about the particular error you are getting. This should fix it, but it would make it easier for us to help if we know exactly what the problem is.

How to respond to SyntaxError in javascript

I get data back from a php server and sometimes it tosses in warnings. These warnings cause the parsing of the response to throw a syntax error which defies all try/catch code I have in place and just stops processing, leaving complex objects in partial states that can't be recovered.
How can I catch these errors? I want to have a chance to get the object back into some steady state.
Ideally, I would not receive answers stating that I should rethink architecture or change php settings. I would like to know how to respond to SyntaxErrors being thrown by JSON.parse().
Thank you,
Jeromeyers
EDIT:
It has come to my attention that the problem is more complex than I originally thought. This is the code that doesn't catch the SyntaxError:
generateSubmissionSuccessCallback: function (reloadOnSave) {
var self = this;
var submissionCallback = function(response) {
var processingError = false;
try
{
var responseObject = {};
if (self.isAspMode())
{
if (typeof response !== 'object') // Chrome auto-parses application/json responses, IE & FF don't
{
response = JSON.parse(response);
}
responseObject = {
entity: response.Payload,
success: response.Success,
message: response.Exception
};
if (jQuery.isArray(response.ValidationErrors))
{
responseObject.message += ' \r\n\r\nValidation Errors\r\n';
for (var i = 0, maxi = response.ValidationErrors.length; i < maxi; i++)
{
var error = response.ValidationErrors[i];
responseObject.message += error.Error + '\r\n';
}
}
}
else
{
responseObject = JSON.parse(response);
}
if (!responseObject || (responseObject.success !== undefined && responseObject.success !== true))
{
processingError = true;
var message = responseObject ? responseObject.message : response;
ErrorHandler.processError(
'An attempt to save failed with following message: \r\n' + message,
ErrorHandler.errorTypes.clientSide,
null,
jQuery.proxy(self.validatingAndSubmittingFinallyFunction, self));
}
else
{
// If this is a parent metaform, reload the entity, otherwise, close the metaform
if (self.metaformType === 'details')
{
if (self.substituteWhatToDoAfterSavingCallback)
{
self.substituteWhatToDoAfterSavingCallback(responseObject);
}
else if (reloadOnSave)
{
self.reloadCurrentEntity(true, responseObject.entity);
}
if (self.doesViewOutlineDefinePostSaveHook())
{
self.viewOutline.functions.postSaveHook(self);
}
}
else if (self.metaformType === 'childDetails')
{
// Reload the Grid by which this form was made
if (self.associatedGridId)
{
Metagrid.refresh(self.associatedGridId);
}
if (self.parentMetaform.associatedGridId && self.childPropertyName)
{
var annotation = self.parentMetaform.getAnnotationByPropertyName(self.childPropertyName);
if (annotation && annotation.hasPropertyOptions('updateParentMetaformAssociatedGrid'))
{
Metagrid.refresh(self.parentMetaform.associatedGridId, self.parentMetaform.entityId);
}
}
if (self.substituteWhatToDoAfterSavingCallback)
{
if (self.doesViewOutlineDefinePostSaveHook())
{
self.viewOutline.functions.postSaveHook(self);
}
self.substituteWhatToDoAfterSavingCallback(responseObject);
}
else
{
if (self.doesViewOutlineDefinePostSaveHook())
{
self.viewOutline.functions.postSaveHook(self);
}
self.disposeMetaform();
}
}
}
}
catch (ex)
{
processingError = true;
ErrorHandler.processError(
"Please immediately inform the authorities that: \r\n\r\n" + typeof response === 'string' ? response : JSON.parse(response) + "\r\n\r\nand:\r\n\r\n " + ex.message,
ErrorHandler.errorTypes.clientSide,
null,
jQuery.proxy(self.validatingAndSubmittingFinallyFunction, self));
}
finally
{
// If we are reporting an error to the user then we can't reset these state variables
// because in the case where this is a child form, the parent will close the form
// before the user has read the error.
if (!processingError)
{
self.validatingAndSubmittingFinallyFunction();
}
}
};
return jQuery.proxy(submissionCallback, self);
}
There's really a lot going on in there, and a lot of structure that it fits into. I don't know if including it will really help.
Assuming you are talking about JSON and it raising an error (and not actual JavaScript being served to the page):
var data;
try{
data = JSON.parse(jsonString);
}catch(e){
// handle the error here, if you like
}
if (typeof data !== "undefined"){
// Yay, we got some!
}
Read more about try...catch at MDN.
For example (from Chrome's console):
> try{ JSON.parse('3/') }catch(e){ console.log('oh no!') }; console.log('OK!')
"oh no!"
"OK!"

Are there any non-fatal javascript errors I can use for testing..?

I'm using window.onerror, and window.onbeforeunload to pass all the errors encountered in the users session with AJAX, I'm trying to test it, and I need to create some javascript errors to test if it is catching it I've tried things like var a = b; (where b doesn't exist) problem is these errors seems to be fatal and stop any further processing...
Can anyone think of a decent way to cause some errors without stopping the processing of the script?
ErrorManager: (function () {
function Init(message) {
InitErrorHandler();
InitAjaxHandler();
}
function InitErrorHandler() {
Data.ErrorHandlerText = "";
Data.ErrorHandlerCount = 0;
window.onerror = function(errorMessage, url, line) {
Data.ErrorHandlerText +"Error: "+(Data.ErrorHandlerCount+1)+" \n\n";
//Get error specific info
Data.ErrorHandlerText += escape(errorMessage) + "\n";
Data.ErrorHandlerText += escape(url) + "\n";
Data.ErrorHandlerText += escape(line) + "\n";
Data.ErrorHandlerCount++;
}
}
function InitAjaxHandler() {
window.onbeforeunload = function() { //when browser closed
if(Data.ErrorHandlerCount > 0) {
SendErrorsToAjax();
}
}
}
function SendErrorsToAjax() {
PrepareErrorsForAjax();
$.getJSON(Interface.PrefixUrl('/sendjserrors/'+Data.ErrorHandlerText), AjaxCallback);
}
function AjaxCallback(response) {
console.log('response of js error ajax request '+response);
}
function PrepareErrorsForAjax() {
var preText = "A user has encountered a few errors: \n\n";
//Get session info
var userAgent, activePageID;
userAgent = escape(navigator.userAgent);
preText += "User agent: "+userAgent+" \n";
if($.mobile.activePage != null) {
activePageID = $.mobile.activePage.attr('id');
preText += "Page ID: "+activePageID+" \n";
}
preText += "\n The following errors were encountered:\n\n";
Data.ErrorHandlerText = preText + Data.ErrorHandlerText;
}
return {
Init: Init,
SendErrorsToAjax: SendErrorsToAjax
}
})(),
All errors are considered fatal in JavaScript. The current code block (<script> tag or external file) is exited and the page continues from the </script> tag onwards.
I am not sure whether a try...catch block would trigger onerror, though.
How about
throw new Error( 'No worries. Just testing...' );
You do have to catch it though if you don't want your program to break.
thanks guys, had a play around after the things you said, as Kolink says, once an error has been encountered, the script basically exits which is far less than ideal.
You can test the onerror thing by:
setTimeout("Interface.ErrorManager.SendErrorsToAjax()", 2000);
var a = b; //create an error
//script exists here, but the timeout still bounces in in a few seconds

Categories

Resources