I want to implement the global error handling for Ajax calls in my angular Js Application . I think $httpprovider works for $http requests only. Kindly guide me in achieving this. How can i write the interceptor for capturing the failure of Ajax calls. My main goal is to capture the failure of Ajax call into google Analytics.
Write ajax call inside javascripts try-catch
http://www.w3schools.com/js/js_errors.asp
You can try to listen to window.onerror event but it will catch all js errors, so you need to filter them.
window.onerror = function(msg, url, line, col, error) {
// Note that col & error are new to the HTML 5 spec and may not be
// supported in every browser. It worked for me in Chrome.
var extra = !col ? '' : '\ncolumn: ' + col;
extra += !error ? '' : '\nerror: ' + error;
// You can view the information in an alert to see things working like this:
alert("Error: " + msg + "\nurl: " + url + "\nline: " + line + extra);
// TODO: Report this error via ajax so you can keep track
// of what pages have JS issues
var suppressErrorAlert = true;
// If you return true, then error alerts (like in older versions of
// Internet Explorer) will be suppressed.
return suppressErrorAlert;
};
You can read more about it in this question.
Related
We have a landing page for mobile customers. And we use window.onerror to catch and log JS errors in this way:
window.onerror = function(message, url, line, col, error) {
log(message + ', ' + error + ', ' + url + ', ' + line + ', ' + col)
}
As a result in our logs we see multiple undefined errors: 'Script error., null, , 0, 0'. I know that such errors may appear in case of CORS problems. When some external script doesn't have "crossorigin=anonymous" attribute. But the problem is that we don't have any external scripts at our landing page.
To double check this we even log the whole page:
log(document.documentElement.outerHTML)
Sometimes browsers insert something into our page. But mostly they don't 😵💫
So what else can cause such undefined error?
Maybe something from the following list?
SVG images such as logo
Google Fonts
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght#300;400;500&family=Cairo&display=swap" rel="stylesheet">
Newest unsupported yet JS features?
UPD 02.07.2022
I have written a web-crawler to test a pre-release website for errors and issues (i.e. missing content type, timeouts, exceptions, redirects).
This morning a colleague asked me to include a check if there was any javascript error on the page...
A pure javascript solution is unlikely -- i.e. detect all JS errors, using JS
What I appear to want to be able to do is capture the javascript console text, ideally via CoreWebView2
If the page logs each exception into an array,
Errors=[]
window.onerror = function (msg, url, line) {
Errors.push("Caught[via window.onerror]: '" + msg + "' from " + url + ":" + line);
return true;
};
Then you can just query the Errors and see both the count and the nature of the errors.
You can also push errors from try catch
I have a need to find out when a warning (not error) message is sent to the browser's console.log . From research, I know that I can detect error messages with JavaScript code similar to this:
window.onerror = function(errorMsg, url, lineNumber){
// any action you want goes here
// errorMsg is the error message itself.
// url should be the file presenting the error, though i have
// found that it only presents to me the address of the site.
// lineNumber is the line number the error occoured on.
// here is an example of what you could do with it:
alert("Error in " + url + " at " + lineNumber + ":\n" + errorMsg);
}
But that only shows error messages. It will not show any warning messages.
Is there a similar way to detect a specific warning message in the console.log? Or, alternately, is there some JS code that will allow me to search the console.log for a specific string?
Note that I can see the warning message in the browser's debugging (console logging) window. But I want to 'intercept' the warning message and perform some action if that warning is found.
Added
The intent is to find out when a specific warning message occurs; the message being similar to "Loading failed for the <script> with source "https://www.example.com/js/somescript.js" .
But the question of how to intercept a warning message (not error; the code I included does that) that is output by the browser (not my code).
Added
So, here's what I need. Assume this code
console.warn("Here is a warning!");
What code would you write to see if that message was written to the console as a warning?
The warnings you are talking about are generated by the browser, not console.warn. This is why you cannot override it. Most likely, you need to manually add listeners for each event you need. For example, if you want to handle a script loading error use the onerror event:
<script src="https://www.example.com/js/somescript1.js" onerror="console.log('Cannot load script from ' + this.src)"></script>
<script src="https://www.example.com/js/somescript2.js" onerror="console.log('Cannot load script from ' + this.src)"></script>
How about overriding the console.log()?
let tmpConsoleLog = console.log;
console.log = function(msg){
// Intercept code goes here using msg variable
alert(msg);
// then perform the normal logging
tmpConsoleLog(msg);
}
console.log("Something");
It's very late, but here's an answer that actually directly answers your question.
var originalConsoleWarn = console.warn;
console.warn = function(message) {
doSomethingWithWarn(message);
originalConsoleWarn(message);
};
function doSomethingWithWarn(message){
console.log("DOING SOMETHING WITH: " + message);
}
console.warn("hi");
So I have a simple WebAPI Controller with...
[HttpGet]
public string Demo()
{
System.Diagnostics.Debug.Print("API Demo call hit " + DateTime.Now.ToString());
return "Got Here";
}
Because of the Debug output, I can tell that it is actually getting called from my javascript. So I know that my script is at least connecting. I also know that if I put a break on the line.. the script (html page) does pause and wait until I let the code continue. So they are talking, but I have 2 issues...
1) Every time I make a send call, I get the script error "NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://localhost:64769/api/demo'" ... even though I know it is talking to it. But I did notice that if I do NOT trap for errors, the script fails on the "Send" line and doesn't continue.
2) However, with the error trap, the script does continue (as expected) but the XMLHttpRequest doesn't have my return. (e.g. responseText is blank).. pretty much every single property of the object is blank or null.
So I think my response is empty because there is a problem with the "send". However because it is actually calling my Controller and waiting on it to run, I'm lost as to what the problem is?
Here is my script...
function CallWebAPI()
{
var displayResults = document.getElementById('responseDetails');
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://localhost:64769/api/demo", false);
try
{
xmlhttp.send();
}
catch(err)
{
displayResults.innerHTML += err + "<br />";
}
displayResults.innerHTML += "The Results...<br />";
for (var key in xmlhttp)
{
displayResults.innerHTML += key + "---" + xmlhttp[key] + "<br />";
}
}
All,
So after an entire day and half of messing around, finally figured it out. I guess I was running an HTML file from my desktop, and my Web Service was running on http://localhost:64769.
This is one of those cross domain things. When using an HTTP client in .NET, I did not have to deal with this.. but once I tried to use a client other than .NET, my Web service actually responded.. but the client Browser would not accept the response.
The fix was to change my api service to...
[HttpGet]
public HttpResponseMessage Demo()
{
string myReturnMessage = "API Demo call hit " + DateTime.Now.ToString();
System.Diagnostics.Debug.Print(myReturnMessage);
HttpResponseMessage myReturn = this.Request.CreateResponse(System.Net.HttpStatusCode.OK, myReturnMessage);
//This was the KEY!!!!
myReturn.Headers.Add("Access-Control-Allow-Origin", "*");
return myReturn;
}
I am quite new to Phantomjs and am starting to getting to know how to use it. However all of the semi advanced tutorials does not cover the thing i want to use Phantomjs for.
Now my question is how would i check if a Javascript is active on the site and if it is working correcly (i.e not throwing erros in the console).
I hope someone is able to point me in the right direction or know how to do this.
you can interact with the open page using the webpage.evaluate method:
var page = require('webpage').create();
page.open('http://m.bing.com', function(status) {
var title = page.evaluate(function(s) {
//what you do here is done in the context of the page
//this console.log will appear in the virtual page console
console.log("test")
//here they are just returning the page title (tag passed as argument)
return document.querySelector(s).innerText;
//you are not required to return anything
}, 'title');
console.log(title);
phantom.exit(); //closes phantom, free memory!
});
in order to see the virtual page console, you have to add a onConsoleMessage callback:
page.onConsoleMessage = function(msg, lineNum, sourceId) {
console.log('CONSOLE: ' + msg + ' (from line #' + lineNum + ' in "' + sourceId + '")');
};
EDIT: by default javascript is executed.