Short version
Trying to write a debug command that returns the call stack, minus the current position. I thought I'd use:
try {
throw new Error(options["msg"])
} catch (e) {
e.stack.shift;
throw (e);
}
but I don't know how to do it exactly. apparently I can't just e.stack.shift like that. Also that always makes it an Uncaught Error — but these should just be debug messages.
Long version
I decided I needed a debug library for my content scripts. Here it is:
debug.js
var debugKeys = {
"level": ["off", "event", "function", "timeouts"],
"detail": ["minimal", "detailed"]
};
var debugState = { "level": "off", "detail": "minimal" };
function debug(options) {
if ("level" in options) {
if (verifyDebugValue("level", options["level"]) == false)
return
}
if ("detail" in options) {
if (verifyDebugValue("detail", options["detail"]) == false)
return
}
console.log(options["msg"]);
}
function verifyDebugValue(lval, rval){
var state = 10; // sufficiently high
for (k in debugKeys[lval]) {
if (debugKeys[lval][k] == rval) {
return true;
}
if (debugKeys[lval][k] == debugState[lval]) { // rval was greater than debug key
return false;
}
}
}
When you using it, you can change the debugState in the code to suit your needs. it is still a work in progress but it works just fine.
To use it from another content script, just load it in the manifest like:
manifest.json
"content_scripts": [
{
"js": ["debug.js", "foobar.js"],
}
],
and then call it like:
debug({"level": "timeouts", "msg": "foobar.js waitOnElement() timeout"});
which generates:
foobar.js waitOnElement() timeout debug.js:17
And there is my problem. At the moment, it is using the console log and so all the debug statements come from the same debug.js line. I'd rather return the calling context. I imagine I need something like:
try {
throw new Error(options["msg"])
} catch (e) {
e.stack.shift;
throw (e);
}
but I don't know how to do it exactly. apparently I can't just e.stack.shift like that. Also that always makes it an Uncaught Error — but these should just be debug messages.
You can't avoid mentioning the line in your debug.js, because either using throw (...) or console.log/error(...) your debug.js will be issuing the command.
What you can do, is have some try-catch blocks in your code, then in the catch block pass the error object to your debug function, which will handle it according to its debugState.
In any case, it is not quite clear how you are using your debug library (and why you need to remove the last call from the stack-trace, but you could try something like this:
Split the stack-trace (which is actually a multiline string) into lines.
Isolate the first line (corresponding to the last call) that is not part of the error's message.
Put together a new stack-trace, with the removed line.
E.g.:
function removeLastFromStack(stack, errMsg) {
var firstLines = 'Error: ' + errMsg + '\n';
var restOfStack = stack
.substring(firstLines.length) // <-- skip the error's message
.split('\n') // <-- split into lines
.slice(1) // <-- "slice out" the first line
.join('\n'); // <-- put the rest back together
return firstLines + restOfStack;
}
function myDebug(err) {
/* Based on my `debugState` I should decide what to do with this error.
* E.g. I could ignore it, or print the message only,
* or print the full stack-trace, or alert the user, or whatever */
var oldStack = err.stack;
var newStack = removeLastFromStack(oldStack, err.message);
console.log(newStack);
//or: console.error(newStack);
}
/* Somewhere in your code */
function someFuncThatMayThrowAnErr(errMsg) {
throw new Error(errMsg);
}
try {
someFuncThatMayThrowAnErr('test');
} catch (err) {
myDebug(err);
}
...but I still don't see how removing the last call from the trace would be helpful
Related
I suspect threadabortexception issue of .NET but I couldn't fix it with possible options.
In short Redirect function throws an errors and goes to the catch, no matter to set the second parameter true or false).
The code below is just an example (but I faced this a couple of times before in real-time projects).
...
try {
var TSD = TriggeredSend.Init("DE_Name");
var Status = TSD.Send(data.subscriber, data.attributes);
if (Status != "OK") {
Platform.Response.Redirect(Variable.GetValue("#error_page"));
} else {
Platform.Response.Redirect(Variable.GetValue("#thanks_page")); //<<<-- This redirect throw error
}
} catch (err) {
Platform.Response.Redirect(Variable.GetValue("#error_page")); // <---- here it comes
}
...
Resources might helps:
1# https://support.microsoft.com/en-us/help/312629/prb-threadabortexception-occurs-if-you-use-response-end-response-redir
2# https://developer.salesforce.com/docs/atlas.en-us.mc-programmatic-content.meta/mc-programmatic-content/ssjs_platformClientBrowserRedirect.htm?search_text=Redirect
Any workaround is welcome.
I know this is an older question but I think it would be good to share findings.
There is no logical explanation to me why this is happen but the Redirect always throws an error and if it is used in a try block, the catch part will be executed.
Here is a simple workaround:
...
try {
var TSD = TriggeredSend.Init("DE_Name");
var Status = TSD.Send(data.subscriber, data.attributes);
try {
if (Status != "OK") {
Platform.Response.Redirect(Variable.GetValue("#error_page"));
} else {
Platform.Response.Redirect(Variable.GetValue("#thanks_page")); //<<<-- This redirect throw error
}
} catch(e) {}
} catch (err) {
Platform.Response.Redirect(Variable.GetValue("#error_page")); // <---- here it comes
}
...
I've got an rxjs observer (really a Subject) that tails a file forever, just like tail -f. It's awesome for monitoring logfiles, for example.
This "forever" behavior is great for my application, but terrible for testing. Currently my application works but my tests hang forever.
I'd like to force an observer change to complete early, because my test code knows how many lines should be in the file. How do I do this?
I tried calling onCompleted on the Subject handle I returned but at that point it's basically cast as an observer and you can't force it to close, the error is:
Object # has no method 'onCompleted'
Here's the source code:
function ObserveTail(filename) {
source = new Rx.Subject();
if (fs.existsSync(filename) == false) {
console.error("file doesn't exist: " + filename);
}
var lineSep = /[\r]{0,1}\n/;
tail = new Tail(filename, lineSep, {}, true);
tail.on("line", function(line) {
source.onNext(line);
});
tail.on('close', function(data) {
console.log("tail closed");
source.onCompleted();
});
tail.on('error', function(error) {
console.error(error);
});
this.source = source;
}
And here's the test code that can't figure out how to force forever to end (tape style test). Note the "ILLEGAL" line:
test('tailing a file works correctly', function(tid) {
var lines = 8;
var i = 0;
var filename = 'tape/tail.json';
var handle = new ObserveTail(filename);
touch(filename);
handle.source
.filter(function (x) {
try {
JSON.parse(x);
return true;
} catch (error) {
tid.pass("correctly caught illegal JSON");
return false;
}
})
.map(function(x) { return JSON.parse(x) })
.map(function(j) { return j.name })
.timeout(10000, "observer timed out")
.subscribe (
function(name) {
tid.equal(name, "AssetMgr", "verified name field is AssetMgr");
i++;
if (i >= lines) {
handle.onCompleted(); // XXX ILLEGAL
}
},
function(err) {
console.error(err)
tid.fail("err leaked through to subscriber");
},
function() {
tid.end();
console.log("Completed");
}
);
})
It sounds like you solved your problem, but to your original question
I'd like to force an observer change to complete early, because my test code knows how many lines should be in the file. How do I do this?
In general the use of Subjects is discouraged when you have better alternatives, since they tend to be a crutch for people to use programming styles they are familiar with. Instead of trying to use a Subject I would suggest that you think about what each event would mean in an Observable life cycles.
Wrap Event Emitters
There already exists wrapper for the EventEmitter#on/off pattern in the form of Observable.fromEvent. It handles clean up and keeping the subscription alive only when there are listeners. Thus ObserveTail can be refactored into
function ObserveTail(filename) {
return Rx.Observable.create(function(observer) {
var lineSep = /[\r]{0,1}\n/;
tail = new Tail(filename, lineSep, {}, true);
var line = Rx.Observable.fromEvent(tail, "line");
var close = Rx.Observable.fromEvent(tail, "close");
var error = Rx.Observable.fromEvent(tail, "error")
.flatMap(function(err) { return Rx.Observable.throw(err); });
//Only take events until close occurs and wrap in the error for good measure
//The latter two are terminal events in this case.
return line.takeUntil(close).merge(error).subscribe(observer);
});
}
Which has several benefits over the vanilla use of Subjects, one, you will now actually see the error downstream, and two, this will handle clean up of your events when you are done with them.
Avoid *Sync Methods
Then this can be rolled into your file existence checking without the use of readSync
//If it doesn't exist then we are done here
//You could also throw from the filter if you want an error tracked
var source = Rx.Observable.fromNodeCallback(fs.exists)(filename)
.filter(function(exists) { return exists; })
.flatMap(ObserveTail(filename));
Next you can simplify your filter/map/map sequence down by using flatMap instead.
var result = source.flatMap(function(x) {
try {
return Rx.Observable.just(JSON.parse(x));
} catch (e) {
return Rx.Observable.empty();
}
},
//This allows you to map the result of the parsed value
function(x, json) {
return json.name;
})
.timeout(10000, "observer timed out");
Don't signal, unsubscribe
How do you stop "signal" a stop when streams only travel in one direction. We rarely actually want to have an Observer directly communicate with an Observable, so a better pattern is to not actually "signal" a stop but to simply unsubscribe from the Observable and leave it up to the Observable's behavior to determine what it should do from there.
Essentially your Observer really shouldn't care about your Observable more than to say "I'm done here".
To do that you need to declare a condition you want to reach in when stopping.
In this case since you are simply stopping after a set number in your test case you can use take to unsubscribe. Thus the final subscribe block would look like:
result
//After lines is reached this will complete.
.take(lines)
.subscribe (
function(name) {
tid.equal(name, "AssetMgr", "verified name field is AssetMgr");
},
function(err) {
console.error(err)
tid.fail("err leaked through to subscriber");
},
function() {
tid.end();
console.log("Completed");
}
);
Edit 1
As pointed out in the comments, In the case of this particular api there isn't a real "close" event since Tail is essentially an infinite operation. In this sense it is no different from a mouse event handler, we will stop sending events when people stop listening. So your block would probably end up looking like:
function ObserveTail(filename) {
return Rx.Observable.create(function(observer) {
var lineSep = /[\r]{0,1}\n/;
tail = new Tail(filename, lineSep, {}, true);
var line = Rx.Observable.fromEvent(tail, "line");
var error = Rx.Observable.fromEvent(tail, "error")
.flatMap(function(err) { return Rx.Observable.throw(err); });
//Only take events until close occurs and wrap in the error for good measure
//The latter two are terminal events in this case.
return line
.finally(function() { tail.unwatch(); })
.merge(error).subscribe(observer);
}).share();
}
The addition of the finally and the share operators creates an object which will attach to the tail when a new subscriber arrives and will remain attached as long as there is at least one subscriber still listening. Once all the subscribers are done however we can safely unwatch the tail.
I have made a following custom logs function to print all console log messages. Using this function I can control with a single flag variable to either print or not logs throughout the app.
var Utilities = {
showLogs: true,
printLog: function (msg) {
if (this.showLogs) {
console.log(msg);
}
}
};
and I call it as:
Utilities.printLog("a message to print on console");
It works fine as expected. But it has one limitation i.e. its not showing the correct line no# and file name where this was called to print the logs.
One solution is to provide extra parameters to print line no# & file name along with the message.
for instance:
Utilities.printLog("a message to print on console", "10","common.js");
Utilities.printLog("a message to print on console", "310","myLib.js");
I dont want these extra parameters and like to know if there is another option available.
Update:
I tried the V8's Stack Trace API http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi but it only helps in cases when an exception is generated inside try catch block.
First override the Error.prepareStackTrace and create a tracing function like this:
Error.prepareStackTrace = function(error, stack) {
return stack;
};
function getTrace(e) {
var stack = e.stack;
var trace = "";
for (var i = 0; i < stack.length; i++) {
trace += "\r" + stack[i];
}
return trace;
}
and created two sample js files.
libObj.js
var libObj = {
getCube: function(x){
return mathLib.cube( x );
}
};
mathLib.js
var mathLib = {
cube: function(x){
return evilObj * x * x; //see the undefined evilObj --- lets catch trace here
}
};
Now from a third js file (or in my case inside the HTML file) I call the function within the try catch block to see the precise trace of the vulnerable code.
<script type="text/javascript">
try {
var results;
results = libObj.getCube(2);
console.log( results );
} catch (e) {
console.log( getTrace(e));
}
</script>
Now I get below trace of the vulnerable code:
Note:- If you do not override the Error.prepareStackTrace then it gives, I think pretty formatted trace...though both have same info.
Without overriding Error.prepareStackTrace:
Now the question remains open, how I can capture similar trace for my custom logs function as defined above.
You could do this:
var Utilities=
{
showLogs:true,
printLog:function(msg){
if(!this.showLogs) return 0;
var k=new Error().stack.split("\n").slice(2);
k.unshift(msg);
console.log(k.join("\n"));
}
}
Take this URL for instance: https://api.eveonline.com/eve/CharacterID.xml.aspx?names=Khan
Using xml2js node.js module you may parse that XML, although it does not look pretty:
var CharacterID = response.eveapi.result[0].rowset[0].row[0].$.characterID;
The app crashed after 2 weeks of running, all because rowset[0] was undefined. Prior to that it crashed because eveapi was not defined. Seriously, does my if-else has to be like this just to prevent server from crashing due to stupid undefined object errors?
if (!response.eveapi ||
!response.eveapi.result[0] ||
!response.eveapi.result[0].rowset[0] ||
!response.eveapi.result[0].rowset[0].row[0]) {
return res.send(500, "Error");
Besides the obvious if (err) return res.send(500, "Error"); error handling where applicable, what is the general practice for undefined errors?
I wrote a library for this kind of thing, called dotty (https://github.com/deoxxa/dotty).
In your case, you could do this:
var dotty = require("dotty");
var CharacterID = dotty.get(response, "eveapi.result.0.rowset.0.row.0.$.characterID");
In the case of the path not being resolvable, it'll just return undefined.
As you've discovered, undefined is not itself an error, but using undefined as an array/object is an error.
x = {'a': { 'b': { 'c': { 'd': [1,2,3,4,5]} } } } ;
try { j = x.a.b.c.e[3] } catch(e) { console.log(e); }
prints
[TypeError: Cannot read property '3' of undefined]
This suggests to me that try/catch can be used with your code to return an error code, and if desired, an error text (or just stick the error text in console.log, a database or local file).
In your case, that could look like:
var CharacterID; // can't define it yet
try {
CharacterID = response.eveapi.result[0].rowset[0].row[0].$.characterID;
} catch(e) {
// send description on the line with error
return res.send(500, "Error: NodeJS assigning CharacterID: "+e);
// return res.send(500, "error"); use this one if you dont want to reveal reason for errors
}
// code here can assume CharacterID evaluated. It might still be undefined, though.
Maybe this function helps?
function tryPath(obj, path) {
path = path.split(/[.,]/);
while (path.length && obj) {
obj = obj[path.shift()];
}
return obj || null;
}
For your code you'd use:
if (tryPath(response,'eveapi.result.0.rows.0.row.0') === null) {
return res.send(500, "Error");
}
jsFiddle example
jsFiddle same example, but as extension to Object.prototype
I'm trying to correctly suppress warnings (alerts) in DataTables. The standard behavior of DataTables is to throw a javascript alert when an error occurs; however, this is currently inconvenient for me. I have been trying to convert the warning to a javascript error by
$.fn.dataTableExt.sErrMode = 'throw';
Which works correctly, but this stops the current javascript execution, which is not what I want. So, I wrapped the DataTables operations (init and changes) in a try-catch with no error handling; however, this also halts the javascript execution. (Tested on Chrome and Firefox)
My question is how do I go about getting rid of these errors/alerts for the purposes of debugging? I'm trying to debug other parts of my script, but these alerts keep on getting in the way.
I modified the native alert using this closure function to redirect DataTables warnings to the console.
window.alert = (function() {
var nativeAlert = window.alert;
return function(message) {
window.alert = nativeAlert;
message.indexOf("DataTables warning") === 0 ?
console.warn(message) :
nativeAlert(message);
}
})();
It restores the window.alert to its native function on first trigger. If you don't want it to restore to the original alert, just comment out the window.alert = nativeAlert; line.
NB: This answer applies to dataTables 1.9.x!
For $.fn.dataTableExt.sErrMode the only value there has any importance is "alert". It is "alert" or anything else. sErrMode is handled by the internal dispatcher function _fnLog, in v1.9.2 about line 4575 in media/js/jquery.dataTables.js :
function _fnLog( oSettings, iLevel, sMesg )
{
var sAlert = (oSettings===null) ?
"DataTables warning: "+sMesg :
"DataTables warning (table id = '"+oSettings.sTableId+"'): "+sMesg;
if ( iLevel === 0 )
{
if ( DataTable.ext.sErrMode == 'alert' )
{
alert( sAlert );
}
else
{
throw new Error(sAlert);
}
return;
}
else if ( window.console && console.log )
{
console.log( sAlert );
}
}
Unfortunelaty, there is no way to override dataTables internal functions, believe me - I have tried, not possible with prototyping or anything else. You can read the author Allan Jardines own comment to that here :
I'm sorry to say that due to how DataTables is constructed at the
moment, it's not possible to override an internal function using
Javascript outside of DataTables scope. This is something that will be
addressed whenever I get around to doing the 2.x series (which might
be a while off!) - but at present you would need to alter the core.
One could think that : Hey, perhaps the iLevel-flag can be changed somewhere in the settings? Again, unfortunately no. iLevel is hardcoded in each internal call to _fnLog.
It is somehow disappointing we have to choose between ugly alerts and completely halt of execution, because an error is thrown. A simply override of window.onerror does not work either. The solution is to modify _fnLog, simply comment out the line where the custom error is thrown :
else
{
// throw new Error(sAlert); <-- comment this line
}
And the execution continues if you have $.fn.dataTableExt.sErrMode = 'throw' (anything else but "alert") and if errors occurs. Even better, one could need those thrown errors in other situations, set a flag outside, like
window.isDebugging = true;
and
else
{
if (!window.isDebugging) throw new Error(sAlert);
}
This is not a "hack" in my opinion, but overruling of a general not avoidable jQuery dataTables behaviour that sometimes is not satisfying. As Allan Jardine himself write in the above link :
Why can't you just modify the source? That's the whole point of open
source :-)
Here's a solution proposed here that's slightly modified and works in v1.10.2 without having to change any vendor files:
$.fn.dataTableExt.sErrMode = "console";
$.fn.dataTableExt.oApi._fnLog = function (oSettings, iLevel, sMesg, tn) {
var sAlert = (oSettings === null)
? "DataTables warning: "+sMesg
: "DataTables warning (table id = '"+oSettings.sTableId+"'): "+sMesg
;
if (tn) {
sAlert += ". For more information about this error, please see "+
"http://datatables.net/tn/"+tn
;
}
if (iLevel === 0) {
if ($.fn.dataTableExt.sErrMode == "alert") {
alert(sAlert);
} else if ($.fn.dataTableExt.sErrMode == "thow") {
throw sAlert;
} else if ($.fn.dataTableExt.sErrMode == "console") {
console.log(sAlert);
} else if ($.fn.dataTableExt.sErrMode == "mute") {}
return;
} else if (console !== undefined && console.log) {
console.log(sAlert);
}
}
try this:
$.fn.DataTable.ext.oApi._fnLog = function (settings, level, msg, tn) {
msg = 'DataTables warning: ' +
(settings !== null ? 'table id=' + settings.sTableId + ' - ' : '') + msg;
if (tn) {
msg += '. For more information about this error, please see ' +
'http://datatables.net/tn/' + tn;
}
console.log( msg );
};
As of DataTables version 1.10.15, you can set $.fn.dataTableExt.errMode to 'ignore' and it will silently ignore the error messages:
$(document).ready(function () {
$.fn.dataTableExt.errMode = 'ignore';
});
_fnLog DataTables function has the following code :
if ( type == 'alert' ) {
alert( msg );
}
else if ( type == 'throw' ) {
throw new Error(msg);
}
else if ( typeof type == 'function' ) {
type( settings, tn, msg );
}
The default value is 'alert' which is problematic.
You can also set to 'throw'. It will create javascript error, but will not do disturb the user.
'ignore' or any other values will just sliently skip the error.
Let me add my 2 cents to davidkonrad's answer above.
One way of modifying _fnLog function without changing the file is to get reference to that method from Api instance in datatables settings:
$.fn.dataTableSettings[0].oApi._fnLog = function(settings, level, msg, tn) {
// Modified version of _fnLog
}
Hope that this will be helpful for someone.