Guest User

Untitled

a guest
Oct 23rd, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. # Throw Your Own Errors
  2.  
  3. Think of errors as built-in failure cases. It is always easier to plan for a failure at a particular point in code than to anticipate failure everywhere. This is common practice in product design, not just code.
  4.  
  5. ## Throwing Errors in JavaScript
  6.  
  7. It is more valuable than any other language. You can throw an error by using the ```throw``` operator and providing an object to throw.
  8. The best way to display a custom error message is to use ```Error``` object.
  9.  
  10. ## Advantage of Throwing Errors
  11.  
  12. Allows you to provide exact text to be displayed instead of just line and column number where the error occured. Always include function name in error message as well as the reason why function failed.
  13.  
  14. ```js
  15.  
  16. function getDivs(element) {
  17. return element.getElementbyTagName('div');
  18. } else {
  19. throw new Error('getDivs(): Argument must be a DOM element.');
  20. }
  21. }
  22.  
  23. ```
  24. Custom error messages clearly show problem. It makes debugging efficient. Think of throwing erros as leaving sticky notes as to why something failed.
  25.  
  26. ## When to throw Errors
  27.  
  28. In general utility functions that are used in numerous places is the best place for custom error, in not private functions.
  29.  
  30. - Once a hard-to-debug error is fixed, add one or to custom erro9rs that can help solve problem should it occur again.
  31.  
  32. - If writing code that can be easily broken, throw an error to prevent it.
  33.  
  34. - If other people might use a function incorrectly, throw errors.
  35.  
  36. The goal is not to prevent errors but to make them easir to debug.
Add Comment
Please, Sign In to add comment