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.
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?)
}
<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/)
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?
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 */
}
Related
How can I catch any exception that occurs in the client side code like "Pause On Caught Exceptions" on chrome developer tools?
I found the solution!
I have used the C# and MVC.
Add a new class to customize your js files bundle like this:
public class CustomScriptBundle : ScriptBundle
{
public CustomScriptBundle(string virtualPath) : base(virtualPath)
{
Builder = new CustomScriptBundleBuilder();
}
public CustomScriptBundle(string virtualPath, string cdnPath)
: base(virtualPath, cdnPath)
{
Builder = new CustomScriptBundleBuilder();
}
}
And, create another class to change the content of the js files as follows::
class CustomScriptBundleBuilder : IBundleBuilder
{
private string Read(BundleFile file)
{
//read file
FileInfo fileInfo = new FileInfo(HttpContext.Current.Server.MapPath(#file.IncludedVirtualPath));
using (var reader = fileInfo.OpenText())
{
return reader.ReadToEnd();
}
}
public string BuildBundleContent(Bundle bundle, BundleContext context, IEnumerable<BundleFile> files)
{
var content = new StringBuilder();
foreach (var fileInfo in files)
{
var contents = new StringBuilder(Read(fileInfo));
//a regular expersion to get catch blocks
const string pattern = #"\bcatch\b(\s*)*\((?<errVariable>([^)])*)\)(\s*)*\{(?<blockContent>([^{}])*(\{([^}])*\})*([^}])*)\}";
var regex = new Regex(pattern);
var matches = regex.Matches(contents.ToString());
for (var i = matches.Count - 1; i >= 0; i--) //from end to start! (to avoid loss index)
{
var match = matches[i];
//catch( errVariable )
var errVariable = match.Groups["errVariable"].ToString();
//start index of catch block
var blockContentIndex = match.Groups["blockContent"].Index;
var hasContent = match.Groups["blockContent"].Length > 2;
contents.Insert(blockContentIndex,
string.Format("if(customErrorLogging)customErrorLogging({0}){1}", errVariable, hasContent ? ";" : ""));
}
var parser = new JSParser(contents.ToString());
var bundleValue = parser.Parse(parser.Settings).ToCode();
content.Append(bundleValue);
content.AppendLine(";");
}
return content.ToString();
}
}
Now, include your js files in application Bundles with your class:
BundleTable.Bundles.Add(new CustomScriptBundle("~/scripts/vendor").Include("~/scripts/any.js"));
Finally, in a new js file write customErrorLogging function as described below, and add it to your project's main html form:
"use strict";
var customErrorLogging = function (ex) {
//do something
};
window.onerror = function (message, file, line, col, error) {
customErrorLogging({
message: message,
file: file,
line: line,
col: col,
error: error
}, this);
return true;
};
Now, you can catch all exceptions in your application and manage them :)
You can use try/catch blocks:
try {
myUnsafeFunction(); // this may cause an error which we want to handle
}
catch (e) {
logMyErrors(e); // here the variable e holds information about the error; do any post-processing you wish with it
}
As the name indicates, you try to execute some code in the "try" block. If an error is thrown, you can perform specific tasks (such as, say, logging the error in a specific way) in the "catch" block.
Many more options are available: you can have multiple "catch" blocks depending on the type of error that was thrown, etc.
More information here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
see a small example how you can catch an Exception:
try {
alert("proper alert!");
aert("error this is not a function!");
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
<body>
<p id="demo"></p>
</body>
put you code in try Block and try to catch error in catch Block.
Hello i try to read somethink from my sqlite in coffe.script when i wrote it JS it works well but now i got some problem
Coffee.script:
I am new in coffeescript and i am wondering what am i doing wrong... Any tips guys ? :)
app.get('/indeks',
(req, res)->
tab = []
i = 0
db = new sqlite3.Database("xxx.sqlite3")
tab = []
i=0
console.log("Jestem przed dbHandler")
db.each("SELECT yyy FROM zzz", #dbHandler, #dbFinal
dbHandler:(err, row)->
console.log("I am in handler dbHandler")
if err
console.log("Error: " + err)
else
tab.push(row)
console.log(row)
dbFinal:()->
console.log("I am in dbFinal")
console.log("Final: " + tab)
console.log("Response")
res.send(tab)
db.close()
)
)
Now code in JS:
app.get('/indeks', function (req, res, next) {
var db = new sqlite3.Database("xxx");
var tab = new Array();
var i=0;
function dbHandler(err, row){
if (err) {
console.log("Error: " + err);
} else {
tab.push(row);
console.log(row);
}
}
function dbFinal(){
console.log("Final: " + tab);
console.log("Response");
res.send(tab);
}
db.each("SELECT zzz FROM yyy", dbHandler, dbFinal);
db.close();
});
Did you look into the transpiled coffee code? When using something like dbHandler:(err, row)-> a JSON-Object with the property dbHandler is generated. This is why you cannot pass dbHandler and dbFinal to the db.each call. This only works when defining a class.
Additionally, you got an unmatched bracket in the line 10 and a bracket too much in the last two lines.
You should always check the compiled code (respectively check whether it even compiles). Here is a helpful site for this. There, you can even convert your JS code to coffeescript.
I am trying to call a stored procedure in java from my .xsjs file. The procedure gets 2 input parameters and returns one. I can call it from an SQL console without any problem by writing:
call "MYSCHEMA"."MyPackage.procedures::addUserC50" ('name', 'lastname', ?)
This is the code in my .xsjs file, I think that it fails in the prepareCall statement. I have tried different combinations (with and without double quotation marks, with and without the name of the schema/package, with and without "(?,?,?)", with and without "{ }".... But nothing works, I always get the 500 Internal server error when I try to execute it.
Does anybody know where the error is or what is the exact syntax for the prepareCall method?
var output = 0,
query = "";
var conn;
var cstmt;
try {
conn = $.db.getConnection();
query = "{ call \"MYSCHEMA\".\"MyPackage.procedures/addUserC50\"(?,?,?) }";
cstmt = conn.prepareCall(query); // <-- Fails
cstmt.setString(1, userName);
cstmt.setString(2, userLastname);
cstmt.execute();
output = cstmt.getInteger(3);
conn.commit();
$.response.status = $.net.http.OK;
$.response.setBody("Successfully created: " + output);
}
catch (e) {
$.response.status = $.net.http.BAD_REQUEST;
$.response.setBody("0");
}
finally {
if (cstmt !== null)
cstmt.close();
if (conn !== null)
conn.close();
}
This is the error that gives back: InternalError: dberror(Connection.prepareCall): 328 - invalid name of function or procedure: MyPackage.procedures/addUserC50: line 1 col 18 (at pos 17) at ptime/query/checker/check_call.cc:21
According to this documentation, it should be something like
var myCallableStatement = myconnection.prepareCall("{call myprocedure(?)}");
Thank you
I managed to make it run, this is the syntax that worked:
query = "call \"MyPackage.procedures::addUserC50\"(?, ?, ?)";
Thank you for your help #shofmn
There could be different reasons why the call is failing. You can investigate your error much easier if you return the error message in the HTTP response. You can do this easily:
try {
// Your code execution here
}
catch (e) {
$.response.contentType = "text/html";
$.response.setBody(e.name + ": " + e.message));
}
If the error message doesn't help you solving the problem, paste the error message in here so that it is more easy for us to investigate as well.
I have searched for several days now, and have tried about every solution that I could find. I know this is something I am not doing correctly, however, I am not sure what the correct way is.
I have an ASP.Net C# web site, running on .Net Framework 4.5. I have a link button on a form, that when clicked fires off a long running process using the ThreadPool. I have a delegate callback setup, and the code does fire when the process is canceled or when it finishes. (I am using the Cancelation Token for canceling the process and the process is Active Reports in case that matters.)
Like I said, everything works great, except for when the callback code fires it does not execute the javascript. (FYI -- this is NOT a javascript callback, just trying to fire off some javascript code when the process finishes.)
Here is the code that i start the report...
string sThreadID = Thread.CurrentThread.ManagedThreadId.ToString();
ThreadPool.QueueUserWorkItem(new WaitCallback(StartReport), cts.Token);
Here is the code for the StartReport....
public static void StartReport(object obj) {
try {
OnTaskCompleteDelegate callback = new OnTaskCompleteDelegate(OnTaskComplete);
BoyceReporting.CallReport(boyce.BoyceThreadingEnvironment.OBRO, "THREADING");
if (boyce.BoyceThreadingEnvironment.CTS.Token.IsCancellationRequested) {
boyce.BoyceThreadingEnvironment.SESSION.sScriptToExecute = "alert('Report Canceled By User');";
callback("CANCELED");
} else {
callback("FINISHED");
}
} catch {
throw;
}
}
Here is the code for the CallBack code.....
public static void OnTaskComplete(string ReportResult) {
try {
sReportResult = ReportResult;
if (ReportResult == "CANCELED") {
// In case we need to do additional things if the report is canceled
}
string sThreadID = Thread.CurrentThread.ManagedThreadId.ToString();
boyce.BoyceThreadingEnvironment.THISPAGE.ClientScript.RegisterStartupScript(boyce.BoyceThreadingEnvironment.THISPAGE.GetType(), "FireTheScript" + DateTime.Now.ToString(), boyce.BoyceThreadingEnvironment.SESSION.sScriptToExecute, true);
ScriptManager.RegisterStartupScript(boyce.BoyceThreadingEnvironment.THISPAGE, boyce.BoyceThreadingEnvironment.THISPAGE.GetType(), "DisplayReport" + DateTime.Now.ToString(), boyce.BoyceThreadingEnvironment.SESSION.sScriptToExecute, true);
} catch {
throw;
}
}
Here is the issue that I am having.....
Everything works fine except i can not get the last line of code to fire the script.
ScriptManager.RegisterStartupScript
Here is what I think is happening.....
From looking at the thread ID, I am sure the reason that the code is not firing is because the ScriptManager code that I am trying to fire in the Call Back event is on a different thread, other than the main thread.
Here is my question(s).....
(1) Am I correct in why this is not firing the JavaScript
(2) How can I (from inside of the CallBack) get this JavaScript to fire? Is there a way to force this to execute on the main Thread?
It's not firing in JS because you're spinning off a new thread. In the meantime, the request has long since returned to the client and closed the connection. By the time the thread tries to write something out to the Response, it's already finished.
Instead of doing it this way, just have your button click (or whatever it is that kicks off the report), inside of an UpdatePanel. Then, you don't need to fire off a new thread.
Here is the cod I used in the C# Code Behind to call the web service to start monitoring this process.
----------------------------------------------------------------------------------------------
CurrentSession.bIsReportRunning = true;
ScriptManager.RegisterStartupScript(this, this.GetType(), "WaitForReport" + DateTime.Now.ToString(), "jsWaitOnCallReport();", true);
MultiThreadReport.RunTheReport(HttpContext.Current, CurrentSession, this, oBRO);
Here is the code that calls the method, using the threadpool, and the method called..
----------------------------------------------------------------------------------------------
ThreadPool.QueueUserWorkItem(new WaitCallback(StartReport), cts.Token);
public static void StartReport(object obj) {
try {
OnTaskCompleteDelegate callback = new OnTaskCompleteDelegate(OnTaskComplete);
BoyceReporting.CallReport(boyce.BoyceThreadingEnvironment.OBRO, "THREADING");
HttpContext.Current = boyce.BoyceThreadingEnvironment.CONTEXT;
if (boyce.BoyceThreadingEnvironment.CTS.Token.IsCancellationRequested) {
boyce.BoyceThreadingEnvironment.SESSION.sScriptToExecute = "alert('Report Canceled By User');";
boyce.BoyceThreadingEnvironment.SESSION.bIsReportRunning = false;
callback("CANCELED");
} else {
boyce.BoyceThreadingEnvironment.SESSION.bIsReportRunning = false;
callback("FINISHED");
}
} catch {
throw;
}
}
Here is the web service method I created to monitor the process, with a built in safety net
--------------------------------------------------------------------------------------------
[WebMethod(EnableSession = true)]
public string WaitOnReport() {
try {
HttpContext.Current = boyce.BoyceThreadingEnvironment.CONTEXT;
SessionManager CurrentSession;
CurrentSession = (SessionManager)boyce.BoyceThreadingEnvironment.SESSION;
DateTime dtStartTime = DateTime.Now;
DateTime dtCurrentTime = DateTime.Now;
if (CurrentSession != null) {
do {
// Build a safety limit into this loop to avoid an infinate loope
// If this runs longer than 20 minutes, then force an error due to timeout
// This timeout should be lowered when they find out what the issue is with
// the "long running reports". For now, I set it to 20 minutes but shoud be MUCH lower.
dtCurrentTime = DateTime.Now;
TimeSpan span = dtCurrentTime-dtStartTime;
double totalMinutes = span.TotalMinutes;
if (totalMinutes>=20) {
return "alert('Error In Creating Report (Time-Out)');";
}
} while (CurrentSession.bIsReportRunning == true);
// If all goes well, return the script to either OPEN the report or display CANCEL message
return CurrentSession.sScriptToExecute;
} else {
return "alert('Error In Creating Report (Session)');";
}
} catch {
throw;
}
}
And here is the JavaScript code I used to initiate the Web Service Call and Also The Postback
--------------------------------------------------------------------------------------------
function jsWaitOnCallReport() {
try {
var oWebService = BoyceWebService.WaitOnReport(jsWaitOnCallReport_CallBack);
} catch (e) {
alert('Error In Calling Report Screen -- ' + e);
}
}
function jsWaitOnCallReport_CallBack(result) {
try {
eval(result);
var myExtender = $find('ModalPopupExtenderPROGRESS');
if (myExtender != null) {
try {
myExtender.hide();
} catch (e) {
// Ignore Any Error That May Be Thrown Here
}
}
$find('PROGRESS').hide();
} catch (e) {
alert('Error In Opening Report Screen -- ' + e);
}
}
Hope this helps someone else out.. Like I said, I am not sure this is the best solution, but it works.. I would be interested in other solutions for this issue to try... Thanks.
I'm building something that includes javascripts on the fly asynchronously, which works, but I'm looking to improve upon the error detection (so all the errors don't just appear to come from some line near the AJAX call that pulls them down.
If I'm using eval to evaluate a multiline javascript file, is there any way to trace which line an error occurs on?
By keeping references to the variables I need when including, I have no problem determining which file the errors occurs in. My problem is determining which line the error occurs in.
Example:
try {
eval("var valid_statement = 7; \n invalid_statement())))");
} catch(e) {
var err = new Error();
err.message = 'Error in Evald Script: ' + e.message;
err.lineNumber = ???
throw err;
}
How can I tell that the error occurred in the second line there?
Specifically I'm interested in doing this in Firefox.
I know that error objects have e.stack in Mozilla browsers, but the output doesn't seem to take into account newlines properly.
The line number in an evaled script starts from the one the eval is on.
An error object has a line number of the line it was created on.
So something like...
try {
eval('var valid_statement = 7; \n invalid_statement())))');
} catch(e) {
var err = e.constructor('Error in Evaled Script: ' + e.message);
// +3 because `err` has the line number of the `eval` line plus two.
err.lineNumber = e.lineNumber - err.lineNumber + 3;
throw err;
}
The global error event-listener will catch the exception from eval and shows the correct line numbers (maybe not in all browsers):
window.addEventListener('error', function(e) {
console.log(e.message
, '\n', e.filename, ':', e.lineno, (e.colno ? ':' + e.colno : '')
, e.error && e.error.stack ? '\n' : '', e.error ? e.error.stack : undefined
);
}, false);
I don't think you can do it with eval reliably. However, you can do this instead of eval:
try {
$("<script />").html(scriptSource).appendTo("head").remove();
} catch (e) {
alert(e.lineNumber);
}
Join the window.addEventListener('error', ...) with document.createElement('script') works for me:
window.addEventListener('error', function(e) {
console.log('Error line:', e.lineno)
}, false);
function runCode (code) {
let js = document.createElement('script')
try {
js.innerHTML = code
document.head.appendChild(js)
}
catch(e) {
// ...
}
document.head.removeChild(js)
}
runCode('// try this:\n1ss') // prints 'Error line: 2'
Thanks to #frederic-leitenberger and #fromin for the solutions parts.