9

If I have a function like the following:

function catchUndefinedFunctionCall( name, arguments )
{
    alert( name + ' is not defined' );
}

and I do something silly like

foo( 'bar' );

when foo isn't defined, is there some way I can have my catch function called, with name being 'foo' and arguments being an array containing 'bar'?

3 Answers 3

10

There is in Mozilla Javascript 1.5 anyway (it's nonstandard).

Check this out:

var myObj = {
    foo: function () {
        alert('foo!');
    }
    , __noSuchMethod__: function (id, args) {
        alert('Oh no! '+id+' is not here to take care of your parameter/s ('+args+')');
    } 
}
myObj.foo();
myObj.bar('baz', 'bork'); // => Oh no! bar is not here to take care of your parameter/s (baz,bork)

Pretty cool. Read more at https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/NoSuchMethod

Sign up to request clarification or add additional context in comments.

3 Comments

This is very cool and nearly exactly what I was looking for - is there an equivalent that works in IE 6+?
As of december 2015, this is an obsolete function that shouldn't be used anymore.
@Loïc what should be used then?
6
try {
 foo();
}
catch(e) {
   callUndefinedFunctionCatcher(e.arguments);
}

UPDATED

passing e.arguments to your function will give you what you tried to pass originally.

4 Comments

arguments is not a property of the Error object, it is a property of functions. In your example e is an error object and so e.arguments will be undefined.
I think it is just that kind of checking the catch-all strategy people want to get away from.
I just ran the following in chrome: try { bar('foo'); } catch(e){ alert(e.arguments); for(x in e) { alert(x) } } it alerts 'foo' and then alerts 'arguments' as a property of e. Am I crazy? Or just still wrong?
doing try/catch in JS is not always a good idea, specially if there are async functions inside the block. Check stackoverflow.com/questions/3677783/…
0
someFunctionThatMayBeUndefinedIAmNotSure ? someFunctionThatMayBeUndefinedIAmNotSure() : throw new Error("Undefined function call");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.