What are the best practices for JavaScript error handling?

前端 未结 5 616
孤城傲影
孤城傲影 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 18:15

    In addition to the other answers: one important thing is to use context data available in JavaScript error objects and in the window.onerror function parameters.

    Things like the stacktrace (errorObject.stack), the filename, the line number and the column number. Note that each browser has some differences...so do your best effort to get nice errors.

    There can even be problems with the console object itself. I use a custom window.onerror function inspired by this one and a special function to trace any given standard error object inspired by this code.

    Another good point is to include the version of your web application somewhere close to the stacktrace (for quick and safe copy and pasting). You may also show errors more aggressively (alert...) in development mode as developers will not constantly monitor the browser console and may not see some of the problems.

    Also use avoid using throw 'My message', use throw new Error('My message'), you can even have custom errors, read this article.

    Always add some context to the errors (the version, the id of the object, some custom message, ...) and also make sure you make a distinction between external errors (some external data or circumstance made your system fail) and internal errors/assertions (your own system messed up), read about 'Design by contract'.

    Here is a guide.

    Also think about using general error handling like interceptors your libs and frameworks:

    • jQuery
    • Angular 1.x and for http
    • Angular 2.x
    • Your new dope framework here ...

提交回复
热议问题