I know there are many other posts about this topic, but I still can't get it working.
I am using Angular 8 in my project and I want to send the browser console message to a server log file.
Could someone please clearifiy does questions for me:
When does the window.onerror get trigged? - right know I put the function within the constructor, is that ok so?
Does it get trigged, if I serve the project local?
window.onerror = function (errorMsg, url, lineNumber) {
alert(errorMsg + ' ' + lineNumber);
};
What do I have to do to get it triggered? (or does for example a thrown error of a missing certificate - trigger this function?)
console.error('test') - does this trigger it?
throw new Error() - or this?
Does Console-Errors like CORS will trigger this function?
I also read that it would get triggered if an img or script source is not avilable.
app.compentent.html: <img src="test.png">
app.copmentent.ts in the constructor (the code of point one)
But I still don't get the alert to display.
I am grateful for any help - thanks
The following may work for you. I used it in some Vue.js code to test triggering window.onerror(). Using eval() should allow you to bypass the compile-time checks of Angular and putting it in window.onload() will ensure it is evaluated after page load.
window.onerror = function (message, source, lineno, colno, error) {
alert('onerror called: ' + message);
}
window.onload = function () {
eval('undefined_function()');
}
As a security note, don't use eval() in production, especially if user input could get anywhere near it.
I've tried triggering error function with your code
window.onerror = function (errorMsg, url, lineNumber) {
alert(errorMsg + ' ' + lineNumber);
};
callingnonexistancefunction()
It is triggering while calling a non exist function.
Hope you'll get some reference
Related
So as the title states I would like to be able to intercept all errors that occur on the page. So starting off with the simplest way:
Add an error event listener to window and store the errors as they occur
The problem with this approach is that if the code that is causing the error is wrapped in a try catch block, the error listener never gets triggered.
A partial solution to this issue is to override the Error constructor so that any time code such as throw new Error() is called we can intercept it using our override. This approach works very nicely for user generated errors, this doesn't work for errors that originate in the browser. For example:
const a = ()=> {
const b = {};
console.log(b.c.d) // Uncaught TypeError: Cannot read property 'c' of undefined
}
try {
a()
} catch(err) {
console.log(err)
}
I would like to be able to detect that a TypeError has been thrown. Overriding the TypeError constructor does not work in this case.
Any ideas?
EDIT: The point is to be able to intercept errors that 3rd party scripts wrap with a try catch
I am learning about the web worker. I am using the follow tutorial
https://developer.mozilla.org/en/docs/Web/Guide/Performance/Using_web_workers
So far, it works. I have the following code
var worker = new Worker('thing.js');
worker.addEventListener('message', function(e) {
alert("Worker said: " + e.data);
}, false);
worker.postMessage("Test me");
and in my thing.js file
self.addEventListener('message', function(e) {
self.postMessage(e.data);
}, false);
The above works fine.
However, I need to pass a message from within my thing.js back to my main js file, to demonstrate it passing back a progress update.
Again, the tutorial shows I can do this, so I have the following updated code
var worker = new Worker('thing.js');
worker.addEventListener('message', function(e) {
alert("Worker said: " + e.data);
}, false);
worker.postMessage("Test me");
and in my thing.js
self.addEventListener('message', function(e) {
self.postMessage(e.data);
}, false);
function DoThisThing() {
postMessage("I should ALSO be working but I am not.");
}
This fails with an error message (in FireBug):
TypeError: Not enough arguments to Window.postMessage.
I can't see what I've done wrong.
It would be convenient to have the full source code that triggered the issue, but I bet the problem was that besides instantiating the worker your code was also including the worker file via a script tag. Something like:
<script type="text/javascript" src="thing.js"></script>
So basically what you have is:
thing.js (worker)
self.addEventListener('message', function(e) {
self.postMessage(e.data);
}, false);
function DoThisThing() {
postMessage("I should ALSO be working but I am not.");
}
DoThisThing();
I assume you were calling DoThisThing() because otherwise you won't get the "TypeError: Not enough arguments to Window.postMessage" error.
If you run the code as it is it works, but you're also seeing the error.
TypeError: Not enough arguments to Window.postMessage.
Worker said: I should ALSO be working but I am not.
Worker said: Test me
So what was triggering the TypeError: Not enough arguments...? If you were sourcing the file from a script tag, the function gets executed two times actually. On the first call, there's an error.
When thing.js gets sourced by the script tag, DoThisThing() gets executed. That's the first call. DoThisThing() calls postmessage (same as self.postmessage). But this call gets resolved to window.postmessage. This method requires a second argument (targetOrigin).
However when the worker gets executed, the call to postmessage (same as self.postmessage) gets resolved to DedicatedWorkerGlobalScope.postmessage. This method doesn't require a second argument.
When you added a second argument to postmessage, you solved the issue for the first call but not the second. Thus you got a new error: "TypeError: Argument 2 of DedicatedWorkerGlobalScope.postMessage can't be converted to a sequence".
Summarizing, there are two types of postmessages, one that belongs to the window object and another one that belongs to the DedicatedWorkerGlobalScope object. A simple call to postmessage gets normally resolved by the DedicatedWorkerGlobalScope object. This call is convenient to communicate workers with their parent. window.postmessage requires a second parameter specifying the targetOrigin. This call is convenient for cross-origin communications.
In your case, the likely cause of the issue was sourcing the worker JavaScript file from a script tag. That caused postmessage to get resolved by window, which required a second argument.
Relatively new to Javascript/Jquery!
tl;dr When I call a function (defined in an external library that I include), my success AND failure callback functions simply do not fire. Given my code below, is this an issue with my javascript or theirs?
I am using an external API along with it's Javascript library, which I include like so:
app/views/layouts/application.html.haml :
= javascript_include_tag 'application'
<script type="text/javascript" src="http://parcelstream.com/api/DmpApi.aspx?map=Bing&services=Utility&host=parcelstream.com/&v=4"></script>
My javascript, which is run on page load:
app/assets/javascripts/mine.js :
function GetByGeometry(point) {
function successCallback(json) {
console.log("success callback called");
// real code here, cut for brevity
}
function errorCallback(error) {
console.log("error callback called");
// real code here, cut for brevity
}
var url = "getByGeometry.aspx?returnGeoType=1&dataSource=SS.Base.Parcels/Parcels&Geo=" + point;
console.log("this is my query URL: " + url);
Dmp.Env.Connections["SS"].getJson(url, successCallback, errorCallback);
}
I am getting no feedback whatsoever. Neither successCallback nor errorCallback are ever fired off, and I am not getting an error either. What am I missing? Is this an error on my end, or is there something wrong with their .getJson() function?
Any insight would be greatly appreciated!
I don't have any clue about the Dmp.Env.Connections["SS"] object, so I cannot tell if that is working or not.
First thing to do is to look into the Network tab (under Developer Tools in Chrome) and check if an Ajax call is fired. This is will tell a lot - if a response is received from the server, if your payload is correct etc. I would start there, and then check for the API definition of Dmp.Env.Connections["SS"] and see if my arguments are correct.
Hope that helps.
I'm making a calculator in Javascript for my school homework and it's using the function eval(). Yes, I know, eval is evil, but I can assure you that I already secured this, so there's no way of exploiting it.
The eval turns the value in textbox into an answer, which is then displayed in another textbox. However, when the syntaxe is wrong (for example, user enters "1++2") I would like if the script displayed some kind of error. But eval() just seems to disappear when the input is unvalid. It returns no value, no error (well, chrome tries explaining it with 'Uncaught Syntaxerror', but that is no use for me) so I have no way to explain to the script what to do, if user messes up the syntaxe.
TL;DR: How do I make the script display an error message, if the eval() has unvalid input?
Thanks in advance
It throws (raises) an exception, which you can catch (handle) and do whatever you want with:
var s;
try
{ s = eval('1++2'); }
catch(e)
{ s = e; }
// now s is either the result, or the exception-info
You should use a try catch block to gracefully show the user that an error has occured.
function evalJS(JsCode)
{
try
{
eval(JsCode);
}
catch(e)
{
alert('The string ' + JsCode + ' contained incorrect JS syntax.');
}
}
evalJS('bogus code');
I have a PhantomJS script that loads a local HTML file, injects some javascript files, then executes some javascript in the context of the page. The javascript that runs generates an exception, but I only get output from the console, which doesn't seem to distinguish between an error and a normal log and doesn't have file, line numbers or a stacktrace.
What I need is a way to capture or otherwise distinguish these errors. I have already tried:
Wrapping my PhantomJS script in a try-catch
Result: nothing is thrown far enough to be caught by this
Define a window.onerror function
Result: nothing happens. WebKit does not implement an onerror event on the window
I would prefer to be able to retrieve the error object itself so that I can retrieve the stacktrace.
I think there were issues with window.onerror not properly working in WebKit (https://bugs.webkit.org/show_bug.cgi?id=8519). Don't know if this has been fixed at all, and if so, if the QT WebKit version is already up-to-date.
However, you should be able to catch the exceptions thrown in your code. If you are using something like webPage.evaluate(...)to run your code, you cannot wrap the complete call in a try/catch block, since the script is evaluated in a different context and the errors will not appear in the main execution context. Insteadyou will need to catch the errors in page execution context. Unfortunately, there is no way of accessing any functions defined in the main context, we therefore have to explicitly write the wrapping code around your code to be executed.
The following is a modified example of the phantomwebintro.js file as included in the PhantomJS source. It loads an HTML page, inserts a script and then runs some code in the page context (here with a line throwing a type error). This code is wrapped with a try/catch block and will return the wrapped result or error object to the main context.
...
// Load an HTML page:
page.open("http://www.phantomjs.org", function(status) {
if (status == "success") {
// Inject some scripts:
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
// Run your own code in the loaded page context:
var resultWrapper = page.evaluate(function() {
var wrapper = {};
try {
// Your code goes here
// ...
var x = undefined.x; // force an error
// store your return values in the wrapper
wrapper.result = 42;
} catch(error) {
wrapper.error = error;
}
return wrapper;
});
// Handle the result and possible errors:
if (resultWrapper.error) {
var error = resultWrapper.error;
console.log("An error occurred: " + error.message);
// continue handling the error
// ...
} else {
var result = resultWrapper.result;
// continue using the returned result
// ...
}
...
});
}
});
...
The solution? return true!
// Error tracking
page.onError = function(msg, trace) {
console.log('= onError()');
var msgStack = [' ERROR: ' + msg];
if (trace) {
msgStack.push(' TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
});
}
console.log(msgStack.join('\n'));
// Consider error fully handled
return true;
};