Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gracefully handle missing elements #296

Open
jwestbrook opened this issue May 7, 2015 · 3 comments
Open

Gracefully handle missing elements #296

jwestbrook opened this issue May 7, 2015 · 3 comments

Comments

@jwestbrook
Copy link
Collaborator

Scenario

document.observe('dom:load',function(){

   $('div1').update('my div')

});

If the element div1 does not exist in the DOM then the js errors and nothing else past that line is ran. The error ends up being cannot read property of null which is not descriptive. (could be different in different browsers but still not the actual problem)

so question is

  1. This is expected behavior, devs should wrap the statements in if blocks
  2. We should throw a better error, "Element with id(s) div1 does not exist"
  3. Gracefully fail, or return an empty element to prevent the JS error and throw a warning

This applies to Element#down() as well

@savetheclocktower
Copy link
Collaborator

This is actually my least favorite thing about jQuery — you can call methods on an empty result set without knowing it's empty. My feeling is that the user will generally want to know if div1 does not exist, because that violates expectations.

In the cases where the user is OK with div1 not existing, then we could introduce something like the Maybe monad. (Though something like that would likely need to rely on ES6 proxies to work.)

Option #2 is interesting, but I'm on the fence about whether it's overkill, since most browsers have good developer tools these days. It's not like the days of IE6 when you had a cryptic error and couldn't trace it back to the proper line number.

@jwestbrook
Copy link
Collaborator Author

I agree that I want to know that an element is missing, sometimes tracking it in minified or uglified code is difficult though and the custom throw would be useful to narrow it down what $() is barfing.

Currently its a cryptic error anyway so throwing a specific error would be an improvement, with minimal effort, and match expectations - ie if I give $() a bad id it will tell me, instead of surprise I get an error about not being able to read a property.

I know you are close to getting the next bugfix out - just wanted to see if a concern one of the devs I know could be addressed.

@savetheclocktower
Copy link
Collaborator

This might be worth doing when a single string is passed into $ just to make debugging a bit easier. I'll put it in the possible enhancements list.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants