I have some simple code that does the job but gives an uncaught error.
ck.setMode('source');
ck.setMode( 'wysiwyg');
This is giving me the message:
Uncaught TypeError: Cannot read property 'on' of undefined
I know it's probably a bad practice but the error does not cause any problems and I would like to avoid it showing in the browser. Is there some way that I could enclose this code so it does not give a browser console alert?
Here's the code that encloses the above:
ngModel.$render = function () {
if (typeof ngModel.$modelValue != 'undefined') {
if (ngModel.$modelValue != null) {
ck.setData(ngModel.$modelValue);
timer = setTimeout(function () {
ck.setData(ngModel.$modelValue);
}, 1000);
timer = setTimeout(function () {
ck.setMode('source');
ck.setMode('wysiwyg');
}, 1000);
}
}
};
You may use code like this:
window.onerror = function(message, url, lineNumber) {
// maybe some handling?
return true; // prevents browser error messages
};
It prevents all error messages, so use it with care.
You can put your code block inside a try catch. So your code would become like this.
try {
ck.setMode('source');
ck.setMode( 'wysiwyg');
}
catch (error) {
// handle your error
}
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
}
...
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
Is it possible to influence errors thrown from the JS compiler? In particular, I want to create my own error type NullPointerException and then proxy the built-in errors (such as Error and TypeError) to potentially return my custom exception.
Consider the following simple attempt (yes, they are global variables – but they are supposed to be):
NullPointerException = function (msg) {
this.message = msg;
};
NullPointerException.prototype.toString = function () {
return "NullPointerException: " + this.message;
};
var ProxyTypeError = TypeError;
TypeError = function (msg) {
if (msg.indexOf('null') === -1) {
return new ProxyTypeError(msg);
}
return new NullPointerException(msg);
};
This will work fine for cases like
throw new TypeError('normal error'); // 'TypeError: normal error'
throw new TypeError('null'); // 'NullPointerException: null'
However, it won't work for the scenario I actually want it to work:
var obj = null;
console.log( obj.someMethod() ); // 'Uncaught TypeError: ...'
I am aware that browsers both use different messages and different errors, as well as that it's sketchy to even be wanting to do any of this. However, I'd still be interested if there is any actual solution to this? In the end, the use-case is something like
try {
// ... code ...
} catch( e ) {
if( e instanceof NullPointerException ) {
// handle NPE separately
}
// do something else
}
wherein I do not have access to the catch part, hence my desire to throw the error accordingly.
Is it possible to influence errors thrown from the JS interpreter?
No. However, if you want to throw your own errors you can do that for all exceptions that happened in your own code:
try {
/* some code, possibly foreign */
var obj = null;
obj.someMethod()
} catch (e) {
throw new CustomTypeError(e.msg);
}
but it would be much better to just check your types:
var obj = null;
if (obj == null)
throw new NullPointerException();
else
obj.someMethod();
I'm trying to find or figure out a way to display in an alert box all of the unhandled javascript exceptions in an application. I'd want all of this to be done on the client side, without using any server side code. I'm using MVC3 as an environment.
I've been researching for the last few days and haven't found exactly what I'm looking for.
I found 2 ways below that seem like they're almost what I'm looking for, except these ways are set up so that you have to pass a function name into a custom method to print the stack trace of all unhandled exceptions within that one specific function. I'm looking for a way to not have to manually pass a function name to a custom method that prints the stack trace of all of the unhandled exceptions. I'd want these custom method to just 'listen' for all unhandled exceptions within the whole application.
http://eriwen.com/javascript/js-stack-trace/
Also something similar to the previous link:
https://github.com/eriwen/javascript-stacktrace
Here's the basic code from the 2nd link above that prints the stack trace of a specified javascript function:
instrumentFunction: function (context, functionName, callback) {
context = context || window;
var original = context[functionName];
context[functionName] = function instrumented() {
callback.call(this, printStackTrace().slice(4));
return context[functionName]._instrumented.apply(this, arguments);
};
context[functionName]._instrumented = original;
}
function printStackTrace(options) {
options = options || {
guess: true
};
var ex = options.e || null,
guess = !! options.guess;
var p = new printStackTrace.implementation(),
result = p.run(ex);
return (guess) ? p.guessAnonymousFunctions(result) : result;
}
So, to sum this up, do you all know of any way to have some sort of 'listener' to listen for all javascript unhandled exceptions and then print them to the screen in an alert box?
Thanks!
Jason
You can do this by using window.onerror method.
window.onerror = function myErrorHandler(errorMsg, url, lineNumber) {
alert("Error occured: " + errorMsg);//or any message
return false;
}
You can either use window.onerror, or (amazingly!) bind to the 'error' event properly:
window.onerror = function (message, file, line, col, error) {
alert("Error occurred: " + error.message);
return false;
};
window.addEventListener("error", function (e) {
alert("Error occurred: " + e.error.message);
return false;
})
If you want to track JavaScript errors, you can try Atatus. I work at Atatus.
In addition to
window.onerror = function (message, file, line, col, error) {
alert("Error occurred: " + error.message);
return false;
};
window.addEventListener("error", function (e) {
alert("Error occurred: " + e.error.message);
return false;
})
You can also catch all the errors fired inside a promise callback (.then()) listening for unhandledrejection event
window.addEventListener('unhandledrejection', function (e) {
alert("Error occurred: " + e.reason.message);
})
Check out http://log4javascript.org it is based on Log4J. If most of your code is wrapped in try/catch statements to handle exceptions you can make use of this library as a common interface for sending output to an always available "dialog box" or logging window that your end user could see. You could even have a button that performs a window.print() to print the contents of the dialog box to the printer or PDF. Good luck.
I'm trying to write handler for uncaught exceptions and browser warnings in Javascript. All errors and warnings should be sent to server for later review.
Handled exceptions can be caught and easily logged with
console.error("Error: ...");
or
console.warn("Warning: ...");
So they are not problem if they are called from javascript code, even more, unhandled exceptions could be caught with this peace of code:
window.onerror = function(){
// add to errors Stack trace etc.
});
}
so exceptions are pretty covered but I've stuck with warnings which browser sends to console. For instance security or html validation warnings. Example below is taken from Google Chrome console
The page at https://domainname.com/ ran insecure content from
http://domainname.com/javascripts/codex/MANIFEST.js.
It would be great if there is some event like window.onerror but for warnings. Any thoughts?
You could just wrap the console methods yourself. For example, to record each call in an array:
var logOfConsole = [];
var _log = console.log,
_warn = console.warn,
_error = console.error;
console.log = function() {
logOfConsole.push({method: 'log', arguments: arguments});
return _log.apply(console, arguments);
};
console.warn = function() {
logOfConsole.push({method: 'warn', arguments: arguments});
return _warn.apply(console, arguments);
};
console.error = function() {
logOfConsole.push({method: 'error', arguments: arguments});
return _error.apply(console, arguments);
};
More Succint Way:
// this method will proxy your custom method with the original one
function proxy(context, method, message) {
return function() {
method.apply(context, [message].concat(Array.prototype.slice.apply(arguments)))
}
}
// let's do the actual proxying over originals
console.log = proxy(console, console.log, 'Log:')
console.error = proxy(console, console.error, 'Error:')
console.warn = proxy(console, console.warn, 'Warning:')
// let's test
console.log('im from console.log', 1, 2, 3);
console.error('im from console.error', 1, 2, 3);
console.warn('im from console.warn', 1, 2, 3);
I know it's an old post but it can be useful anyway as others solution are not compatible with older browsers.
You can redefine the behavior of each function of the console (and for all browsers) like this:
// define a new console
var console = (function(oldCons){
return {
log: function(text){
oldCons.log(text);
// Your code
},
info: function (text) {
oldCons.info(text);
// Your code
},
warn: function (text) {
oldCons.warn(text);
// Your code
},
error: function (text) {
oldCons.error(text);
// Your code
}
};
}(window.console));
//Then redefine the old console
window.console = console;
I needed to debug console output on mobile devices so I built this drop-in library to capture console output and category and dump it to the page. Check the source code, it's quite straightforward.
https://github.com/samsonradu/Consolify
In the same function that you are using to do console.log(), simply post the same message to a web service that you are recording the logs on.
You're going about this backwards. Instead of intercepting when an error is logged, trigger an event as part of the error handling mechanism and log it as one of the event listeners:
try
{
//might throw an exception
foo();
}
catch (e)
{
$(document).trigger('customerror', e);
}
function customErrorHandler(event, ex)
{
console.error(ex)
}
function customErrorHandler2(event, ex)
{
$.post(url, ex);
}
this code uses jQuery and is oversimplified strictly for use as an example.