Log minified JavaScript errors in production code - javascript

I am running a back-end app with a React JS frontend on our intranet. I don't want to use services like Sentry or Rollbar to keep track of minified code in production because I don't want to upload our source-maps externally.
Are there any self-hosted solutions for tracking & logging errors in JS source-maps?

We are using a combination of JSNLog and Stacktrace. This is what goes into the <head> of your index.html:
<script src="~/js/jsnlog.min.js"></script>
<script src="~/js/stacktrace.min.js"></script>
<script src="~/js/stacktraceConfig.js"></script>
And below the contents of stacktraceConfig.js:
window.onerror = function (msg, file, line, col, error) {
var callback = function (stackframes) {
var stringifiedStack = stackframes.map(function (sf) {
return sf.toString();
}).join('\n');
JL('serverLog').fatalException({
msg: 'Exception! ' + stringifiedStack,
1: '--------------------------------------------------------------',
errorMsg: msg,
url: stackframes[0].fileName + ":" + stackframes[0].lineNumber,
functionName: stackframes[0].functionName,
lineNumber: stackframes[0].lineNumber,
column: stackframes[0].column,
x: '--------------------------------------------------------------',
}, error);
};
var errback = function (err) { console.log(err.message); };
StackTrace.fromError(error).then(callback).catch(errback);
// Tell browser to run its own error handler as well
return false;
};
You will have to configure JSNLog yourself to have it send the errors by mail.

Related

Best place to store JavaScript variable to be easily accessible from Nightwatch tests?

I'm writing a javascript library and when some event happens I would like to store a JSON variable that can be accessed from NightwatchJs tests to validate the data that the event generated.
I used to store it as a global variable (ex.
window.debugLog = { message: "something", timestamp: 1111, eventType: "click", other: "stuff" }; )
and retrieve it in nightwatch with
browser.execute("return window.debugLog;", [], function(result){ debugLog = result.value;})
Unfortunately this doesn't seem reliable with every browser/device when I run Nightwatch tests over Browserstack. It's not rare to have false positives because Appium failed to execute the Js function.
I was wondering if anyone has suggestions about more reliable alternatives. A cookie? A metatag? An hidden tag?
Write it to a file, require that file for the later tests that use it.
I have, in the custom_commands folder, a file called helperFunctions.js, and within that, this is one of the more useful functions/methods:
saveToFile : function(client, path, data) {
this.fs = fs;
buffer = new Buffer(data);
fs.open(path, 'w', function(err, fd) {
if (err) {
throw 'error opening file: ' + err;
}
fs.write(fd, buffer, 0, buffer.length, null, function(err) {
if (err) throw 'error writing file: ' + err;
return fs.close(fd, function() {
console.log('File write: ' + path + ' has been updated.' );
})
});
})
},
In that way it can be called to write data from within any test:
this.helperFunctions.saveToFile(client, "conf/usefulVariable.js", "module.exports = {\"default\" : {},\"test_env\" : { myGlobal: " + someGlobal + "}};")
In the test file that needs to use it:
var usefulVar = require("../conf/usefulVariable.js");
You may need/want to JSON.stringify or parse as appropriate.

how to add a basic keen.io event with javascript

I am trying to set up a basic example that sends a custom keen.io event via js. At the moment I do not need any presentation, visualisation, etc.
Here is the example that I created from another one I found online. I attempted several variations, and all of them work in Google Chrome, but none of them works in Firefox (38.0 for Ubuntu canonical - 1.0).
if I add to the head the inline script (!function(a,b){a("Keen"...) as it is proposed in the manual, I do not get any errors in FF, but it seems that addEvent never gets called and it produces no response, "err" nor "res".
if I include the library from the CDN (d26b395fwzu5fz.cloudfront.net/3.2.4/keen.min.js), I get an error when the page is loaded:
ReferenceError: Keen is not defined
var keenClient = new Keen({
If I download the js file and serve it locally, after the button is clicked, I get the following error response:
Error: Request failed
err = new Error(is_err ? res.body.message : 'Unknown error occurred');
All of these attempts work from Chrome, but I need this to work from other browsers too.
I received a response from keen.io team. It turned out that Adblock Plus is interfering with the script. After I disabled it everything works in FF as in Chrome.
After some investigation in turned out that request to http://api.keen.io was blocked by "EasyPrivacy" filter of ABP with these filter rules: keen.io^$third-party,domain=~keen.github.io|~keen.io
So, sending a request to an "in-between" server (a proxy) seems to be the only solution that I can see.
We have a bit specific use case - a need to track a static site and also an available access to a rails api server, but the solution we ended up using may come useful to someone.
error.html
<html>
<head>
<title>Error</title>
<script src="/js/vendor/jquery-1.11.2.min.js"></script>
<script src="/js/notification.js"></script>
<script type="text/javascript">
$(document).on('ready', function () {
try {
$.get(document.URL).complete(function (xhr, textStatus) {
var code = xhr.status;
if (code == 200) {
var codeFromPath = window.location.pathname.split('/').reverse()[0].split('.')[0];
if (['400', '403', '404', '405', '414', '416', '500', '501', '502', '503', '504'].indexOf(codeFromPath) > -1) {
code = codeFromPath;
}
}
Notification.send(code);
});
}
catch (error) {
Notification.send('error.html', error);
}
});
</script>
</head>
<body>
There was an error. Site Administrators were notified.
</body>
</html>
notification.js
var Notification = (function () {
var endpoint = 'http://my-rails-server-com/notice';
function send(type, jsData) {
try {
if (jsData == undefined) {
jsData = {};
}
$.post(endpoint, clientData(type, jsData));
}
catch (error) {
}
}
// private
function clientData(type, jsData) {
return {
data: {
type: type,
jsErrorData: jsData,
innerHeight: window.innerHeight,
innerWidth: window.innerWidth,
pageXOffset: window.pageXOffset,
pageYOffset: window.pageYOffset,
status: status,
navigator: {
appCodeName: navigator.appCodeName,
appName: navigator.appName,
appVersion: navigator.appVersion,
cookieEnabled: navigator.cookieEnabled,
language: navigator.language,
onLine: navigator.onLine,
platform: navigator.platform,
product: navigator.product,
userAgent: navigator.userAgent
},
history: {
length: history.length
},
document: {
documentMode: document.documentMode,
documentURI: document.documentURI,
domain: document.domain,
referrer: document.referrer,
title: document.title,
URL: document.URL
},
screen: {
width: screen.width,
height: screen.height,
availWidth: screen.availWidth,
availHeight: screen.availHeight,
colorDepth: screen.colorDepth,
pixelDepth: screen.pixelDepth
},
location: {
hash: window.location.hash,
host: window.location.host,
hostname: window.location.hostname,
href: window.location.href,
origin: window.location.origin,
pathname: window.location.pathname,
port: window.location.port,
protocol: window.location.protocol,
search: window.location.search
}
}
}
}
return {
send: send
}
}());
example of sending notification manually from js code:
try {
// some code that may produce an error
}
catch (error) {
Notification.send('name of keen collection', error);
}
rails
# gemfile
gem 'keen'
#routes
resource :notice, only: :create
#controller
class NoticesController < ApplicationController
def create
# response to Keen.publish does not include an ID of the newly added notification, so we add an identifier
# that we can use later to easily track down the exact notification on keen
data = params['data'].merge('id' => Time.now.to_i)
Keen.publish(data['type'], data) unless dev?(data)
# we send part of the payload to a company chat, channel depends on wheter the origin of exception is in dev or production
ChatNotifier.notify(data, dev?(data)) unless data['type'] == '404'
render json: nil, status: :ok
end
private
def dev?(data)
%w(site local).include?(data['location']['origin'].split('.').last)
end
end

Why I get "Uncaught ReferenceError: require is not defined"?

I want to use lolapi, so I went with my terminal to folder where project is and did npm install lolapi.
My code is a really simple cordova app:
HTML:
<body>
<div class="app">
<h1> Lol App</h1>
</div>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/lolJ.js"></script>
</body>
JavaScript (lolJ.js):
var options = {
useRedis: true,
hostname: '127.0.0.1',
port: 6379,
cacheTTL: 7200
};
var lolapi = require('lolapi')('***-***-***-***-***', 'euw', options);
lolapi.setRateLimit(10, 500);
var summonerName = 'Wickd';
lolapi.Summoner.getByName(summonerName, function (error, summoner) {
if (error) throw error;
/* summoner object
{ Wickd:
{
id: 71500,
name: 'Wickd',
profileIconId: 613,
summonerLevel: 30,
revisionDate: 1408199475000
}
} */
console.log(summoner);
console.log(summoner[summonerName]);
var summonerId = summoner[summonerName].id;
lolapi.Summoner.getRunes(summonerId, function (error, runes) {
if (error) throw error;
// do something with runes
})
});
I replaced Wickd with my lol username, but still nothing happens.
As you can see I'm really new to this, so please, any guide will be great
Thanks
The require syntax is what's referred to as CommonJS, the default way of how you load modules within Node.js environments.
In order to use the require syntax in a browser environment you'd need to use tools like Browserify which handles this for you by bundling your application together with your dependencies.

getting stuck ,Log in with facebook with firebase

i try to login with facebook in firebase using java script and html. i also create a facebook application and set app secret and app id in firebase dashbord.
and all the other setting in facebook app that firebase said in their doc
but im getting this.
<html>
<head>
<script src='https://cdn.firebase.com/js/client/2.0.4/firebase.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
</head>
<body>
<div id='messagesDiv'></div>
<input type='text' id='nameInput' placeholder='Name'>
<input type='text' id='messageInput' placeholder='Message'>
<script>
var myDataRef = new Firebase('https://fiery-inferno-9432.firebaseio.com/');
myDataRef.authWithOAuthPopup("facebook", function(error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
}
});
myDataRef.authWithOAuthRedirect("facebook", function(error, authData) {
if (error) {
console.log("Ridi Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
}
});
$('#messageInput').keypress(function (e) {
if (e.keyCode == 13) {
var name = $('#nameInput').val();
var text = $('#messageInput').val();
myDataRef.push({name: name, text: text});
$('#messageInput').val('');
}
});
myDataRef.on('child_added', function(snapshot) {
var message = snapshot.val();
displayChatMessage(message.name, message.text);
});
function displayChatMessage(name, text) {
$('<div/>').text(text).prepend($('<em/>').text(name+': ')).appendTo($('#messagesDiv'));
$('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight;
};
</script>
</body>
</html>
im getting
Login Failed! Error: There are no login transports available for the requested method.code: "TRANSPORT_UNAVAILABLE"message: "There are no login transports available for the requested method."stack: (...)get stack: function () { [native code] }set stack: function () { [native code] }proto: dconstructor: function Error() { [native code] }message: ""name: "Error"toString: function toString() { [native code] }proto: Object
i found the problem. i must run the html file by running a file server
simply by this on cmd
python -m SimpleHTTPServer
and then run html by
http://localhost/test.html
From https://www.firebase.com/docs/web/guide/user-auth.html:
Note: Browser popups and redirects are not available on all platforms
or browser environments. Popups are not available in Chrome for iOS,
iOS Preview Panes, or local, file:// URLs.
Also, when authenticating via popup on PhoneGap / Cordova apps, including cordova.js and the InAppBrowser plugin in the scope of the page are both required.
I solved it by running my page via server on localhost instead of running the file directly from file system.

hapi.js best way to handle errors

I'm creating my first node.js REST web service using hapi.js. I'm curious as to the best way to handle errors let's say from my dao layer. Do i throw them in my dao layer and then just try/catch blocks to handle them and send back errors in my controller, or is there a better way that the cool kids are handling this?
routes/task.js
var taskController = require('../controllers/task');
//var taskValidate = require('../validate/task');
module.exports = function() {
return [
{
method: 'POST',
path: '/tasks/{id}',
config : {
handler: taskController.createTask//,
//validate : taskValidate.blah
}
}
]
}();
controllers/task.js
var taskDao = require('../dao/task');
module.exports = function() {
return {
/**
* Creates a task
*
* #param req
* #param reply
*/
createTask: function createTask(req, reply) {
taskDao.createTask(req.payload, function (err, data) {
// TODO: Properly handle errors in hapi
if (err) {
console.log(err);
}
reply(data);
});
}
}();
dao/task.js
module.exports = function() {
return {
createTask: function createTask(payload, callback) {
... Something here which creates the err variable...
if (err) {
console.log(err); // How to properly handle this bad boy
}
}
}();
Generic Solution w/ Fully Customisable Error Template/Messages
We wrote a Hapi Plugin that handles all errors seamlessly: npmjs.com/package/hapi-error
It lets you define your own custom error pages in 3 easy steps.
1. Install the plugin from npm:
npm install hapi-error --save
2. Include the plugin in your Hapi project
Include the plugin when you register your server:
server.register([require('hapi-error'), require('vision')], function (err) {
// your server code here ...
});
See: /example/server_example.js for simple example
3. Ensure that you have a View called error_template
Note: hapi-error plugin expects you are using Vision (the standard view rendering library for Hapi apps)
which allows you to use Handlebars, Jade, React, etc. for your templates.
Your error_template.html (or error_template.ext error_template.jsx) should make use of the 3 variables it will be passed:
errorTitle - the error tile generated by Hapi
statusCode - *HTTP statusCode sent to the client e.g: 404 (not found)
errorMessage - the human-friendly error message
for an example see: /example/error_template.html
That's it! Now your Hapi App handles all types of errors and you can throw your own custom ones too!
Note: hapi-error works for REST/APIs too. if the content type header (headers.acceps) is set to application/json then your app will return a JSON error to the client, otherwise an HTML page will be served.
In doing more research along with Ricardo Barros' comment on using Boom, here's what I ended up with.
controllers/task.js
var taskDao = require('../dao/task');
module.exports = function() {
return {
/**
* Creates a task
*
* #param req
* #param reply
*/
createTask: function createTask(req, reply) {
taskDao.createTask(req.payload, function (err, data) {
if (err) {
return reply(Boom.badImplementation(err));
}
return reply(data);
});
}
}();
dao/task.js
module.exports = function() {
return {
createTask: function createTask(payload, callback) {
//.. Something here which creates the variables err and myData ...
if (err) {
return callback(err);
}
//... If successful ...
callback(null, myData);
}
}();
I think the cool kids now use a package to caught unhandled errors with Hapi, I present to you, Poop.
The only thing Poop is missing is some rich documentation, but check it out, and you'll see that Poop is great.
Some of my friends went to a node.js event in Lisbon, on of the hosts was a guy in charge of web technology stack at Wallmart, they use Hapi.js, Poop and some other cool things.
So if they use poop it must be pretty awesome.
PS: The name is suppa awesome

Categories

Resources