JavaScript 错误处理的最佳实践是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6484528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:58:37  来源:igfitidea点击:

What are the best practices for JavaScript error handling?

javascripterror-handling

提问by Joshua Cody

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, and throw, but I'm not finding a ton of advice from experts on when and where to throw errors.

我期待开始做我的JavaScript多一点错误的证明,而且我发现很多文档的使用trycatchfinally,和throw,但我不是专家在何时何地抛出错误找一吨的建议。

  • Should every piece of code be wrapped in a try/catch?
  • Is there more advice like this onat what point errors ought to be caught?
  • Are there disadvantages to raising errors instead of having code fail silently in production?
  • This has been touched on on SO as far as implementations, but have server-logging JS errors an effective strategy?
  • Anything else I ought to know, regarding trapping errors in my application?
  • 是否应该将每段代码都包装在 try/catch 中?
  • 关于应该在什么时候发现错误,是否有更多这样的建议?
  • 引发错误而不是让代码在生产中静默失败是否有缺点?
  • 就实现而言,这已经涉及到 SO,但是服务器记录 JS 错误是否是一种有效的策略?
  • 关于在我的应用程序中捕获错误,我还应该知道什么?

I'm also completely game for hearing of books that have great chapters or in-depth explanations of error-handling. Eloquent JavaScripttouches on the matter, but isn't very prescriptive or opinionated about the issue.

我也完全喜欢听那些有很棒的章节或对错误处理有深入解释的书。Eloquent JavaScript触及了这个问题,但在这个问题上不是非常规范或固执己见。

Thanks for any advice you can give!

感谢您提供的任何建议!

回答by cdmdotnet

An immensely interesting set of slides on Enterprise JavaScript Error Handling can be found at http://www.devhands.com/2008/10/javascript-error-handling-and-general-best-practices/

可以在http://www.devhands.com/2008/10/javascript-error-handling-and-general-best-practices/找到一组非常有趣的关于企业 JavaScript 错误处理的幻灯片

In short it summarizes:

简而言之,它总结了:

  1. Assume your code will fail
  2. Log errors to the server
  3. You, not the browser, handle errors
  4. Identify where errors might occur
  5. Throw your own errors
  6. Distinguish fatal versus non-fatal errors
  7. Provide a debug mode
  1. 假设你的代码会失败
  2. 将错误记录到服务器
  3. 您,而不是浏览器,处理错误
  4. 确定可能发生错误的位置
  5. 抛出你自己的错误
  6. 区分致命错误和非致命错误
  7. 提供调试模式

The slides go into much more detail and most probably will give you some direction.

幻灯片更详细,很可能会给你一些指导。

UPDATE

更新

The presentation mentioned above can be found here: http://www.slideshare.net/nzakas/enterprise-javascript-error-handling-presentation

上面提到的演示文稿可以在这里找到:http: //www.slideshare.net/nzakas/enterprise-javascript-error-handling-presentation

回答by Jens Roland

Nicholas Zakas of Yahoo! fame did a talk on Enterprise Error Handling (slides) at Ajax Experience 2008, in which he proposed something like this:

雅虎的尼古拉斯·扎卡斯!在 Ajax Experience 2008 上,Fame 做了一个关于企业错误处理(幻灯片)的演讲,他在演讲中提出了这样的建议:

function log(sev,msg) {
    var img = new Image();
    img.src = "log.php?sev=" +
        encodeURIComponent(sev) +
        "&msg=" + encodeURIComponent(msg);
}

// usage
log(1, "Something bad happened.")

// Auto-log uncaught JS errors
window.onerror = function(msg, url, line) {
    log(1, msg);
    return true;
}

A year later, Nicholas Zakas posted an update on his blogwhich included a clever pattern to inject error handling code automatically on your production environment (using aspect-oriented programming).

一年后,Nicholas Zakas在他的博客上发布了一个更新,其中包括一个聪明的模式,可以在您的生产环境中自动注入错误处理代码(使用面向方面的编程)。

When you start logging window.error calls, you're going to notice two things:

当您开始记录 window.error 调用时,您会注意到两件事:

  1. If your site is fairly complex, you're going to log a lotof errors
  2. You'll be seeing a bunch of useless "window.error in undefined:0" messages
  1. 如果你的网站相当复杂,你会记录很多错误
  2. 你会看到一堆无用的“window.error in undefined:0”消息

Reducing the torrent of log entries is as simple as testing for severity and/or a random number before logging to the server:

减少日志条目的洪流就像在登录到服务器之前测试严重性和/或随机数一样简单:

function log(sev,msg) {
    if (Math.random() > 0.1) return; // only log some errors

    var img = new Image();
    img.src = "log.php?sev=" +
        encodeURIComponent(sev) +
        "&msg=" + encodeURIComponent(msg);
}

Handling the useless "window.error in undefined:0" errors depends on your site architecture, but can try identifying all Ajax calls and throwing an exception when something fails (possibly returning a stack trace using stacktrace.js).

处理无用的“window.error in undefined:0”错误取决于您的站点架构,但可以尝试识别所有 Ajax 调用并在出现故障时抛出异常(可能使用stacktrace.js返回堆栈跟踪)。

回答by JMax

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

IHMO,您应该像在其他几种语言(AFAIK:Python、Java)中一样在 javascript 中使用错误处理。

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 :

为了更好的可读性(以及可能更好的性能,即使我不确定它是否有很大的影响),您应该主要在以下情况下使用 try / catch 块:

  • 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 debugwithout bothering the final user
  • 您要包装的代码部分是整个算法的关键部分。如果失败,它可能:

    • 在代码的下一部分上创建错误(例如,因为缺少 var ......)
    • 使页面看起来不像预期的那样(对内容或 css 的影响)
    • 使结果对用户来说显得陌生(影响代码行为)
  • 您知道您编写的代码与所有浏览器不兼容

  • 您计划代码可能会失败(因为没有其他方法可以通过 if...then... 块来检查它是否应该工作)
  • 并且当您想在不打扰最终用户的情况下进行调试

Eventually, javascript experts may have other elements to give.

最终,javascript 专家可能会提供其他元素。

my 2 cents to the box,

我的 2 美分到盒子里,

Regards,

问候,

Max

最大限度

回答by Christophe Roussy

In addition to the other answers: one important thing is to use context dataavailable in JavaScript error objects and in the window.onerrorfunction parameters.

除了其他答案:一件重要的事情是使用JavaScript 错误对象和window.onerror函数参数中可用的上下文数据

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.

诸如堆栈跟踪 (errorObject.stack)、文件名、行号和列号之类的东西。请注意,每个浏览器都有一些差异......所以尽你最大的努力来获得好的错误。

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

控制台对象本身甚至可能存在问题。我使用受此启发的自定义 window.onerror 函数和受此代码启发的特殊函数来跟踪任何给定的标准错误对象。

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.

另一个好处是将 Web 应用程序的版本包含在靠近堆栈跟踪的地方(以便快速安全地复制和粘贴)。您还可以在开发模式下更积极地显示错误(警告...),因为开发人员不会经常监视浏览器控制台,并且可能看不到某些问题。

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

也使用避免使用throw 'My message',使用throw new Error('My message'),你甚至可以有自定义错误,阅读这篇文章

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 force made your system fail) and internal errors/assertions (your own system messed up), read about 'Design by contract'.

始终为错误添加一些上下文(版本、对象的 id、一些自定义消息,...),并确保区分外部错误(某些外部数据或强制使您的系统失败)和内部错误/assertions(你自己的系统搞砸了),阅读“按合同设计”。

Here is a guide.

这是一个指南

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

还要考虑使用一般的错误处理,比如你的库和框架的拦截器: