What are the best practices for JavaScript error handling?

前端 未结 5 574
孤城傲影
孤城傲影 2021-01-29 17:25

I\'m looking to start making my JavaScript a bit more error proof, and I\'m finding plenty of documentation on using try, catch, finally,

5条回答
  •  天涯浪人
    2021-01-29 17:54

    IHMO, you should use error handling in javascript like you do in several other languages (AFAIK: Python, Java).

    For better readability (and probably better performance, even though I am not sure it has a really big impact), you should use the try / catch block mostly on the following cases :

    • The part of the code you want to wrap is a key part of the whole algorithm. If it fails, it could :

      • create errors on the next part of the codes (e.g. because a var is missing...)
      • make the page not look what expected (impact on content or css)
      • make the results appear strange to the user (impact on the code behavior)
    • You know that the code you are writing is not compatible with every browser

    • You planned that the code may fail (because there is no other way to check that it should work by if...then... blocks)
    • And also when you want to debug without bothering the final user

    Eventually, javascript experts may have other elements to give.

    my 2 cents to the box,

    Regards,

    Max

提交回复
热议问题