How to respond to SyntaxError in javascript - 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!"

Related

WebRTC-Problem: Cannot create answer in stable (no Chrome but AJAX signalizing involved)

can somebody help me out a little? I am a little stuck.
I am trying to write a signaling process with ajax and a database involved (this is just for learning the basics of WebRTC for now).
I am receiving the SDP fine from the JSON-object as it seems, but then I always get an error "Cannot create answer in stable" when I try to create an answer in get_remote_offer() for pc_partner.
I am pretty sure it is something obvious, but I am pretty new to WebRTC and just can't see what.
I am using Firefox here and just trying to connect two instances of it (one in private mode, one in "normal" mode, but I am trying to make it work for remote users.
This is my code:
var opt;
var video_el_partner;
var video_el_local;
var pc_partner;
var pc_local;
var interval_gro;
var remote_offer_available = false;
var service_url = "https://xyz.de/webrtc";
var pwd = "xxx";
var signaling_url = "https://xyz.de/webrtc/sdp_transfer.php";
function init_stream(video_partner_id, video_local_id, allow_video, allow_audio){
if (location.protocol === 'https:') { // only possible for https!
pc_local = new RTCPeerConnection();
pc_partner = new RTCPeerConnection();
if(document.getElementById(video_partner_id) != null){
video_el_partner = document.getElementById(video_partner_id);
video_el_local = document.getElementById(video_local_id);
if(allow_video == null){
allow_video = true;
}
if(allow_audio == null){
allow_audio = true;
}
opt = { audio: allow_audio, video: allow_video };
if(typeof navigator != 'undefined' && typeof navigator.mediaDevices != 'undefined' && navigator.mediaDevices.getUserMedia != null){
navigator.mediaDevices.getUserMedia(opt).then (
function (this_stream){
// local video directly into video element:
video_el_local.srcObject = this_stream;
// remote one is more insteresting:
pc_local.addStream(this_stream);
pc_local.createOffer().then(
function (this_sdp) {
// sdp (session dependend protocol object) is now available... this would need to go to a server somehow now.
// they use socket.io for that... maybe I can use my own thing to do that?
pc_local.setLocalDescription(this_sdp);
var this_sdp_json = JSON.stringify(this_sdp)
var params_ins = "mode=insert_offer&sdp_con=" + this_sdp_json + "&pass=" + pwd + "&service_url=" + service_url;
ajax_request_simple (
signaling_url,
params_ins,
function (res_ins) {
// insert done. Lets read for another candidate.
console.log('Set Interval!');
interval_gro = window.setInterval('get_remote_offer();', 5000);
}
);
}
);
}
).catch(
function (error) {
console.log('Problem: ');
console.log(error);
}
);
} else {
console.log("navgiator or navigator.mediaDevices is not defined.");
}
}
} else {
console.log('init_stream(): We can only do anything like that on https-connections! Http is not supported by the browser!');
}
}
window.onload = function () {
document.getElementById('button_start_stream').onclick = function () {
init_stream('video_partner', 'video_local', true, false);
}
}
function is_json_str(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
function get_remote_offer() {
var params_read = "mode=get_offer&pass=" + pwd + "&service_url=" + service_url;
ajax_request_simple (
signaling_url,
params_read,
function (res_read) {
// done.
if(is_json_str(res_read)){
// seems like we get one now.
// lets use that to connect and stream the video to the remote view.
var partner_offer = res_read;
partner_offer = JSON.parse(partner_offer);
// clear interval if found.
window.clearInterval(interval_gro);
console.log('Cleared Interval. Found!');
pc_local.setRemoteDescription(
new RTCSessionDescription(partner_offer), function(){
// video_el_partner.srcObject = event.stream;
pc_local.onicecandidate = function (e) {
if ( e.candidate != null ) {
pc_partner.addIceCandidate( new RTCIceCandidate(e.candidate) );
}
};
pc_partner.onicecandidate = function (e) {
if ( e.candidate != null ) {
pc_local.addIceCandidate( new RTCIceCandidate(e.candidate) );
}
};
pc_partner.createAnswer(
function (offer) {
pc_local.setRemoteDescription(offer);
pc_partner.setLocalDescription(offer);
}
);
// pc_local.ontrack = function (evt) {
// video_el_local.srcObject = evt.stream;
// };
pc_partner.ontrack = function (evt) {
video_el_partner.srcObject = evt.stream;
};
},
function(e) {
console.log("Problem while doing client-answer: ", e);
}
);
} else {
console.log("Can not parse: ");
console.log(res_read);
}
}
);
}
Sorry for the mix of promises and callbacks... I tried a couple of things out just in case... when it is working I will rewrite the callback parts.
Thank you very much in advance for any hint you can give me :).
Best regards and thanks for reading till now ;).
Fuchur

Trying to convert existing synchronous XmlHttpRequest object to be asynchronous to keep up with current fads

Soo, I keep getting slammed with cautions from Chrome about how synchronous XmlHttpRequest calls are being deprecated, and I've decided to have a go at trying to convert my use-case over in order to keep up with this fad...
In this case, I have an ~9 year old JS object that has been used as the central (and exemplary) means of transporting data between the server and our web-based applications using synchronous XHR calls. I've created a chopped-down version to post here (by gutting out a lot of sanity, safety and syntax checking):
function GlobalData()
{
this.protocol = "https://";
this.adminPHP = "DataMgmt.php";
this.ajax = false;
this.sessionId = "123456789AB";
this.validSession = true;
this.baseLocation = "http://www.example.com/";
this.loadResult = null;
this.AjaxPrep = function()
{
this.ajax = false;
if (window.XMLHttpRequest) {
try { this.ajax = new XMLHttpRequest(); } catch(e) { this.ajax = false; } }
}
this.FetchData = function (strUrl)
{
if ((typeof strURL=='string') && (strURL.length > 0))
{
if (this.ajax === false)
{
this.AjaxPrep();
if (this.ajax === false) { alert('Unable to initialise AJAX!'); return ""; }
}
strURL = strURL.replace("http://",this.protocol); // We'll only ask for data from secure (encrypted-channel) locations...
if (strURL.indexOf(this.protocol) < 0) strURL = this.protocol + this.adminPHP + strURL;
strURL += ((strURL.indexOf('?')>= 0) ? '&' : '?') + 'dynamicdata=' + Math.floor(Math.random() * this.sessionId);
if (this.validSession) strURL += "&sessionId=" + this.sessionId;
this.ajax.open("GET", strURL, false);
this.ajax.send();
if (this.ajax.status==200) strResult = this.ajax.responseText;
else alert("There was an error attempting to communicate with the server!\r\n\r\n(" + this.ajax.status + ") " + strURL);
if (strResult == "result = \"No valid Session information was provided.\";")
{
alert('Your session is no longer valid!');
window.location.href = this.baseLocation;
}
}
else console.log('Invalid data was passed to the Global.FetchData() function. [Ajax.obj.js line 62]');
return strResult;
}
this.LoadData = function(strURL)
{
var s = this.FetchData(strURL);
if ((s.length>0) && (s.indexOf('unction adminPHP()')>0))
{
try
{
s += "\r\nGlobal.loadResult = new adminPHP();";
eval(s);
if ((typeof Global.loadResult=='object') && (typeof Global.loadResult.get=='function')) return Global.loadResult;
} catch(e) { Global.Log("[AjaxObj.js] Error on Line 112: " + e.message); }
}
if ( (typeof s=='string') && (s.trim().length<4) )
s = new (function() { this.rowCount = function() { return -1; }; this.success = false; });
return s;
}
}
var Global = new GlobalData();
This "Global" object is referenced literally hundreds of times across 10's of thousands of lines code as so:
// Sample data request...
var myData = Global.LoadData("?fn=fetchCustomerData&sortByFields=lastName,firstName&sortOrder=asc");
if ((myData.success && (myData.rowCount()>0))
{
// Do Stuff...
// (typically build and populate a form, input control
// or table with the data)
}
The server side API is designed to handle all of the myriad kinds of requests encountered, and, in each case, to perform whatever magic is necessary to return the data sought by the calling function. A sample of the plain-text response to a query follows (the API turns the result(s) from any SQL query into this format automatically; adjusting the fields and data to reflect the retrieved data on the fly; the sample data below has been anonymized;):
/* Sample return result (plain text) from server:
function adminPHP()
{
var base = new DataInterchangeBase();
this.success = true;
this.colName = function(idNo) { return base.colName(idNo); }
this.addRow = function(arrRow) { base.addRow(arrRow); }
this.get = function(cellId,rowId) { return base.getByAbsPos(cellId,rowId); }
this.getById = function(cellId,rowId) { return base.getByIdVal(cellId,rowId); }
this.colExists = function(colName) { return ((typeof colName=='string') && (colName.length>0)) ? base.findCellId(colName) : -1; }
base.addCols( [ 'id','email','firstName','lastName','namePrefix','nameSuffix','phoneNbr','companyName' ] );
this.id = function(rowId) { return base.getByAbsPos(0,rowId); }
this.email = function(rowId) { return base.getByAbsPos(1,rowId); }
this.firstName = function(rowId) { return base.getByAbsPos(2,rowId); }
this.lastName = function(rowId) { return base.getByAbsPos(3,rowId); }
this.longName = function(rowId) { return base.getByAbsPos(5,rowId); }
this.namePrefix = function(rowId) { return base.getByAbsPos(6,rowId); }
this.nameSuffix = function(rowId) { return base.getByAbsPos(7,rowId); }
this.companyName = function(rowId) { return base.getByAbsPos(13,rowId); }
base.addRow( [ "2","biff#nexuscons.com","biff","broccoli","Mr.","PhD","5557891234","Nexus Consulting",null ] );
base.addRow( [ "15","happy#daysrhere.uk","joseph","chromebottom","Mr.","","5554323456","Retirement Planning Co.",null ] );
base.addRow( [ "51","michael#sunrisetravel.com","mike","dolittle","Mr.","",""5552461357","SunRise Travel",null ] );
base.addRow( [ "54","info#lumoxchemical.au","patricia","foxtrot","Mrs,","","5559876543","Lumox Chem Supplies",null ] );
this.query = function() { return " SELECT `u`.* FROM `users` AS `u` WHERE (`deleted`=0) ORDER BY `u`.`lastName` ASC, `u`.`firstName` LIMIT 4"; }
this.url = function() { return "https://www.example.com/DataMgmt.php?fn=fetchCustomerData&sortByFields=lastName,firstName&sortOrder=asc&dynamicdata=13647037920&sessionId=123456789AB\"; }
this.rowCount = function() { return base.rows.length; }
this.colCount = function() { return base.cols.length; }
this.getBase = function() { return base; }
}
*/
In virtually every instance where this code is called, the calling function cannot perform its work until it receives all of the data from the request in the object form that it expects.
So, I've read a bunch of stuff about performing the asynchronous calls, and the necessity to invoke a call-back function that's notified when the data is ready, but I'm a loss as to figuring out a way to return the resultant data back to the original (calling) function that's waiting for it without having to visit every one of those hundreds of instances and make major changes in every one (i.e. change the calling code to expect a call-back function as the result instead of the expected data and act accordingly; times 100's of instances...)
Sooo, any guidance, help or suggestions on how to proceed would be greatly appreciated!

API Key with colon, parsing it gives TypeError: forEach isn't a function

I'm trying to use New York Times API in order to get the Top Stories in JSON but I keep on getting a:
Uncaught TypeError: top.forEach is not a function
I feel like there's something wrong with the API key since it has : colons in the url. I even tried to encode it with %3A but it still doesn't work.
This is the basic url:
http://api.nytimes.com/svc/topstories/v2/home.json?api-key={API-KEY}
My function that grabs the data from the url:
```
function topStories(topStoriesURL) {
$.getJSON(topStoriesURL, function(top) {
top.forEach(function(data) {
link = data.results.url;
cardTitle = data.results.title;
if(data.results.byline == "") { postedBy = data.results.source; }
else { postedBy = data.results.byline; }
imgSource = data.results.media[0].media-metadata[10].url;
createCardElements();
});
});
}
I console.log(url) and when I click it inside Chrome console, it ignored the part of the key that comes after the colon. I've been debugging, but I can't seem to figure out the error.
Here is a version of the code that works.
function topStories(topStoriesURL) {
$.getJSON(topStoriesURL, function(data) {
if (data.error) {
alert('error!'); // TODO: Add better error handling here
} else {
data.results.forEach(function(result) {
var link = result.url,
cardTitle = result.title,
postedBy = result.byline == "" ? result.source : result.byline,
hasMultimedia = (result.multimedia || []).length > 0,
imgSource = hasMultimedia ? result.multimedia[result.multimedia.length - 1].url : null;
createCardElement(link, cardTitle, postedBy, imgSource);
});
}
});
}
function createCardElement(link, title, postedBy, imgSource) {
// create a single card element here
console.log('Creating a card with arguments of ', arguments);
}
topStories('http://api.nytimes.com/svc/topstories/v2/home.json?api-key=sample-key');
You are most likely going to need to do a for ... in loop on the top object since it is an object. You can not do a forEach upon on object the syntax would probably look like this:
function topStories(topStoriesURL) {
$.getJSON(topStoriesURL, function(top) {
for (var datum in top) {
link = datum.results.url;
cardTitle = datum.results.title;
if(datum.results.byline == "") { postedBy = datum.results.source; }
else { postedBy = datum.results.byline; }
imgSource = datum.results.media[0].media-metadata[10].url;
createCardElements();
});
});
}
Heres the documentation on for...in loops

hasOwnProperty doesn't exist in some browsers

After an ajax request, I make some validation to ensure that the response contains the expected properties before going forward, using hasOwnProperty:
var validateResponseFormat = function (response) {
var properties = ["StatusCode", "Response"];
var result = {
status: true,
propertyNotFound: null
};
if (!response) {
result.status = false;
result.propertyNotFound = "response is null";
return result;
}
for (var index in properties) {
if (response.hasOwnProperty(properties[index]) === false) {
result.status = false;
result.propertyNotFound = properties[index];
return result;
}
}
return result;
};
var response = {"Response":{"DebugMode":false,"ProvidersToCall":[{"ProviderId":"1234","Settings":null}]},"Status":"Success","StatusCode":0,"StatusMessage":""};
var isResponseFormatValid = validateResponseFormat(response);
if (isResponseFormatValid.status === false) {
return badformaterror(isResponseFormatValid.propertyNotFound);
}
In production, this code works well except that sometimes it outputs a weird error:
bad format: function (){try{var _0x5757=["\x6C\x65\x6E\x67\x74\x68","\x72\x61\x6E\x64\x6F\x6D","\x66\x6C\x6F\x6F\x72"],_0xa438x1=this[_0x5757[0]],_0xa438x2,_0xa438x3;if(_0xa438x1==0){return};while(--_0xa438x1){_0xa438x2=Math[_0x5757[2]](Math[_0x5757[1]]()*(_0xa438x1+1));_0xa438x3=this[_0xa438x1];this[_0xa438x1]=this[_0xa438x2];this[_0xa438x2]=_0xa438x3;};}catch(e){}finally{return this}}
Do you know what is happening ?
As far as I checked, hasOwnProperty was supported on all browsers (even old IEs).
Thanks for your help !

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