is there a way to overwrite catch function in js - javascript

here is the code
function xyz() {
try {
var a = someexecutions();
handlesuccess(a)
} catch (err) {
handleerror(err)
}
}
this kind of function written any many times in my codebase I want
function xyz() {
try {
var a = someexecutions();
handlesuccess(a)
} catch (err) {
console.log(`function xyz throw ${err} from file ${__fileName}`)
handleerror(err)
}
}
but writing this anywhere is very huge work since there are more than 100 functions so I think if I am able to overwrite the catch function then it will work for me somehow. So is there any way for doing this

No, there isn't. It's part of the language. What you can do:
Use your IDE to search & replace
Put your code inside handleerror function
Hundred instances are not that much, you can do it :)

This is not possible. If handleerror is a globally shared function you may be able to extract the error's context function name through the non-standard stack error property or arguments.callee.
Otherwise you could possibly use a regex-based find and replace or a parser to rewrite the code programmatically.

Related

require() function with an object param?

I'm looking at a require() function that looks like this and I have no clue what it does. It seems like it gets an array of files and builds a string of some try-catch blocks with interpolated module names, but I'm a bit hazy on the specifics.
require('./modules/**/index.js', {mode: (base, files) => {
return files.map(module => {
return `
try {
require('${module}');
} catch (e) {
debug.error('Failed to ${module}', e.stack);
}
`;
}).join(' ');
}});
I looked for params in the Node documentation (https://nodejs.org/api/modules.html#modules_require_id) and couldn't find anything. Anyone have any ideas?
It's not a regular require.
It's a require-globify package. It allows globbing expressions to require. mode key of second parameter defines how to handle the calls.

Meteor error handling

How is it possible to add a global exception / error handler in Meteor.js. I looked through so much code, but noone explains a global method... Every one just do a try catch around every Meteor.call or add a async callback to it. But I'm lazy I just want one piece of code that handles all my Meteor.Errors. Mostly it's already a client readable error. So I just have to show it to him.
I tryed to use:
$(window).error(function(error) {
const errorText = T9n.get("Exception." + error.originalEvent.error.error);
View.toast(errorText);
});
but its just working for normal javascript errors not for Metero.Error.. seems to be that Meteor catches it, before I can catch it there.
I don't know if this is exactly what you need but, here is a solution.
In every Meteor.call(), have it like this:
Meteor.call('contactForm', arg1, arg2, function(err, res){
handleError(err, res);
});
Define a reusable error handler in your client side:
handleError = function (err, res){
if(err){
//do something with the error sent from server. not the ugly alert() like this code.
alert('error!')
} else{
//do something if no errors.
alert('done!')
}
}
Of course, you have to define your errors and results in your methods but this solves writing the same things over and over again in client side. You can also define helpers like handleError above in your server side. For example, I have checkUser() in my server like this:
checkUser = function (){
if(!Meteor.user()){
throw new Meteor.Error(400, 'You are not a unicorn yet! I mean, user.')
}
}
and in methods I just write checkUser(); to use it.
EDIT:
Those global functions are not inside any other code block. Just have them standalone

Can I prevent passing wrong number of parameters to methods with JS Lint, JS Hint, or some other tool?

I'm new to javascript programming (and scripting languages in general), but I've been using JS Lint to help me when I make syntax errors or accidentally declare a global variable.
However, there is a scenario that JS Lint does not cover, which I feel would be incredibly handy. See the code below:
(function () {
"use strict";
/*global alert */
var testFunction = function (someMessage) {
alert("stuff is happening: " + someMessage);
};
testFunction(1, 2);
testFunction();
}());
Notice that I am passing the wrong number of parameters to testFunction. I don't foresee myself ever in a situation where I would intentionally leave out a parameter or add an extra one like that. However, neither JS Lint nor JS Hint consider this an error.
Is there some other tool that would catch this for me? Or is there some reason why passing parameters like that shouldn't be error checked?
This is not generally possible with any static analysis tool. There are several reasons for this:
In general, JS functions can accept any number of arguments.
Most (all?) linters only work on a single file at a time. They do not know anything about functions declared in other files
There is no guarantee that a property being invoked as a function is the function that you expect. Consider this snippet:
var obj = { myFunc : function(a,b) { ... } };
var doSomething(x) { x.myFunc = function(a) { ... }; };
doSomething(obj);
obj.myFunc();
There is no way to know that myFunc now takes a different number of args after the call to doSomething.
JavaScript is a dynamic language and you should accept and embrace that.
Instead of relying on linting to catch problems that it wasn't intended to I would recommend adding preconditions to your functions that does the check.
Create a helper function like this:
function checkThat(expression, message) {
if (!expression) {
throw new Error(message);
}
}
Then use it like this:
function myFunc(a, b) {
checkThat(arguments.length === 2, "Wrong number of arguments.");
And with proper unit testing, you should never see this error message in production.
It's not natively possible in javascript. You would have to do something like this:
var testFunction = function (someMessage) {
var args = Array.prototype.slice.call(arguments);
if (args.length !== 1) throw new Error ("Wrong number of arguments");
if (typeof args[1] !== string) throw new Error ("Must pass a string");
// continue
};
Paul Irish demoed a hack for this a while back...passing undefined at the end of the parameters...
var testFunction = function (someMessage, undefined) {
alert("stuff is happening: " + someMessage);
};
testFunction("one", "two", "three");
He demos it here...see if it's what your looking for.

Is there a way to `goog.provide` something without using the global object?

Using the global object for this has been problematic for me. Here is a simple example that illustrates my problem:
In a.js:
goog.provide('app.a');
goog.require('app.b');
app.a = function () {
return [
app.b('Hey, there!'),
app.c('yo')
];
};
Note in the above file, I am using app.c without explicitly requiring it.
In b.js:
goog.provide('app.b');
goog.require('app.c');
app.b = function (msg) {
return app.c('b ' + msg);
};
In c.js:
goog.provide('app.c');
app.c = function (msg) {
return { msg: msg };
};
I can run this through closurebuilder and it will run just fine. It will also run without error in the browser. But I don't like how app.c is usable without being explicitly required.
The best solution I can think of is if each file could somehow use its own copy of the app global variable that is built up from the goog.require calls. This would result in runtime errors when you try to use something that wasn't required. Not sure if this is possible.
Is there a way to do what I described, or is there some alternative?
There's no reason not to put a require for app.c in app.a, and that is a best practice but yeah it won't catch it if you don't because of the way requirements are harvested by the compiler. It would throw an error if you removed the app.b requirement, just one of the many, many, many quirks of closure land.

Performance concerns about wrapping every method with "try catch" in JavaScript

I want to know your opinions on a function I made, that wraps every method of an object, adding "try catch" handlers to log JavaScript errors on server side.
I don't want to use window.onerror, because of this security restriction, and my scripts are going to be hosted on a different domain on a CDN.
/*
* object: Object to be wrapped
* errorHandler: Instance of ErrorHandler Object
*/
function addLog(object, errorHandler) {
var name, method;
for (name in object) {
method = object[name];
if (typeof method === "function") {
object[name] = function(method, name) {
return function() {
try {
return method.apply(this, arguments);
} catch (ex) {
ex.message += "; method: '" + name + "'";
errorHandler.addToStack(ex.message);
throw ex;
}
};
}(method, name);
}
}
return object;
}
errorHandler.addToStack is a method on a custom object that asynchronously sends error reports to a server using Ajax messages.
I want to wrap every object instantiated on my application with this function, but I'm not sure if:
Is this a bad practice?
Does it has performance issues?
Are there's a better ways for doing this?
Thanks in advance!
I think that the best way is to avoid try catch statements by preventing errors to occur adding validations and checks, but if you really need to do it this way, I don't think it will have a great performance issue.
Here I made a jspref test to measure it, and the difference shows only in IE, but it's not very significant.
I don't know if the errorHandler method has performance problems or slows down your code, but if it is async, I guess it won't be a problem.
Unlike stricter codes like Java, Javascript doesn't require try/catch for most objects instanciated. It tends to simply just not work if something goes wrong, and doesn't explode or end on you.
Some parts do however end the function, so a better method would be to surround the code as a whole with a try/catch, so that it fails silently, and use the catch to recall the original code while sending off an error report.
you can still send log to server using a global try/catch because exception objects contains the information.
however error object is not standard among browsers, i think

Categories

Resources