sudeshna kadu
sudeshna kadu

Reputation:

How to catch exceptions in javascript?

I want to catch exceptions in javascript if an insertion query is not done.

I have written the code below:

var adoConn = new ActiveXObject("ADODB.Connection");
var adoRS = new ActiveXObject("ADODB.Recordset");
var rec = new ActiveXObject("ADODB.Record");
adoConn.Open="DRIVER={MySQL ODBC 3.51 Driver};SERVER=172.25.37.145;" + "DATABASE=confluence;UID=root;PASSWORD=somePassword;OPTION=3";
//Connectionstring
alert('Database Connected');
adoConn.Execute("insert into `session` (SessionId,Timestamp) values ('"+SessionId+"','"+SessionCurrenttime+"')");

If I get the same session id then the query was not executed as it is the primary key in the database.

Upvotes: 14

Views: 15905

Answers (4)

scunliffe
scunliffe

Reputation: 63676

To be complete, here's the full structure

try {
  // your code that can throw exception goes here
} catch(e) {
  //do stuff with the exception
} finally {
  //regardless if it worked or not, do stuff here (cleanup?)
}

Upvotes: 26

marktucks
marktucks

Reputation: 1761

try {
  // your code that can throw exception goes here
} catch(e) {
  //do stuff with the exception
}

FYI - the code you posted looks, well, for want of a better word, ugly! (No offense) Couldn't you use DWR or some other JavaScript framework (depending on your language choice) to hide all the DB connection stuff at the back end and just have the javascript calling the back end code and doing something with the response?

Upvotes: 2

KooiInc
KooiInc

Reputation: 122986

try {
    adoConn.Execute("insert into session (SessionId,Timestamp) values ('"
                     + SessionId + "','" 
                     + SessionCurrenttime + "')");
} catch(e) {
    /*use error object to inspect the error: e.g. return e.message */
}

Upvotes: 1

tehvan
tehvan

Reputation: 10369

<script language="JavaScript">

try
{
 colours[2] = "red";
}
catch (e)
{
  alert("Oops! Something bad just happened. Calling 911...");
}

</script> 

(Ripped from http://www.devshed.com/c/a/JavaScript/JavaScript-Exception-Handling/)

Upvotes: 3

Related Questions