[关闭]
@qinyun 2018-11-23T06:09:56.000000Z 字数 11994 阅读 1220

JavaScript错误处理权威指南

未分类


作者|Lukas Gisder-Dubé
译者|谢丽

本文将分三部分分析JavaScript中的错误,首先我们将了解错误的一般情况。之后,我们将关注后端(Node.js + Express.js)。最后,我们将重点看下,如何处理React.js中的错误。我选择这些框架,因为它们是目前最流行的,但是,你应该能够将新发现轻松地应用到其他框架中!

继上一篇文章(https://link.medium.com/MO32x55aNR)之后,我想谈谈错误。错误很好——我相信你以前听过这个说法。乍一看,我们害怕错误,因为错误往往会涉及到在公共场合受到伤害或羞辱。通过犯错误,我们实际上学会了如何不去做某事,以及下次如何做得更好。

显然,这是关于从现实生活的错误中学习。编程中的错误有点不同。它们为我们提供了很好的特征来改进我们的代码,并告诉用户什么地方出了问题(也可能是教他们如何修复它)。

GitHub上提供了一个完整的样例项目。

JavaScript错误和一般处理

throw new Error('something went wrong') 会在JavaScript中创建一个错误实例,并停止脚本的执行,除非你对错误做了一些处理。当你作为JavaScript开发者开启自己的职业生涯时,你自己很可能不会这样做,但是,你已经从其他库(或运行时)那里看到了,例如,类似“ReferenceError: fs未定义”这样的错误。

Error对象

Error对象有两个内置属性供我们使用。第一个是消息,作为参数传递给Error构造函数,例如new Error(“这是错误消息”)。你可以通过message属性访问消息:

  1. const myError = new Error(‘请改进代码’)
  2. console.log(myError.message) // 请改进代码

第二个是错误堆栈跟踪,这个属性非常重要。你可以通过stack属性访问它。错误堆栈将为你提供历史记录(调用堆栈),从中可以查看哪个文件导致了错误。堆栈的上部也包括消息,然后是实际的堆栈,从距离错误发生最近的点开始,一直到最外层“需要为错误负责”的文件:

  1. Error: 请改进代码
  2. at Object.<anonymous> (/Users/gisderdube/Documents/_projects/hacking.nosync/error-handling/src/general.js:1:79)
  3. at Module._compile (internal/modules/cjs/loader.js:689:30)
  4. at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
  5. at Module.load (internal/modules/cjs/loader.js:599:32)
  6. at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
  7. at Function.Module._load (internal/modules/cjs/loader.js:530:3)
  8. at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
  9. at startup (internal/bootstrap/node.js:266:19)
  10. at bootstrapNodeJSCore (internal/bootstrap/node.js:596:3)

抛出和处理错误

现在,Error实例本身不会导致任何结果,例如,new Error('...')不会做任何事情。当错误被抛出时,就会变得更有趣。然后,如前所述,脚本将停止执行,除非你在流程中以某种方式对它进行了处理。记住,是手动抛出错误,还是由库抛出错误,甚至由运行时本身(Node或浏览器),都没有关系。让我们看看如何在不同的场景中处理这些错误。

try .... catch

这是最简单但经常被遗忘的错误处理方法——多亏async / await,它的使用现在又多了起来。它可以用来捕获任何类型的同步错误,例如,如果我们不把console.log(b)放在一个try … catch块中,脚本会停止执行。

  1. const a = 5
  2. try {
  3. console.log(b) // b is not defined, so throws an error
  4. } catch (err) {
  5. console.error(err) // will log the error with the error stack
  6. }
  7. console.log(a) // still gets executed

… finally

有时候,不管是否有错误,代码都需要执行。你可以使用第三个可选块finally。通常,这与在try…catch语句后面加一行代码是一样的,但它有时很有用。

  1. const a = 5
  2. try {
  3. console.log(b) // b is not defined, so throws an error
  4. } catch (err) {
  5. console.error(err) // will log the error with the error stack
  6. } finally {
  7. console.log(a) // will always get executed
  8. }

异步性——回调

异步性,这是在使用JavaScript时必须考虑的一个主题。当你有一个异步函数,并且该函数内部发生错误时,你的脚本将继续执行,因此,不会立即出现任何错误。当使用回调函数处理异步函数时(不推荐),你通常会在回调函数中收到两个参数,如下所示:

如果有错误,err参数就等同于那个错误。如果没有,参数将是undefined或null。要么在if(err)块中返回某项内容,要么将其他指令封装在else块中,这一点很重要,否则你可能会得到另一个错误,例如,result可能未定义,而你试图访问result.data,类似这样的情况。

  1. myAsyncFunc(someInput, (err, result) => {
  2. if(err) return console.error(err) // we will see later what to do with the error object.
  3. console.log(result)
  4. })

异步性——Promises

处理异步性的更好方法是使用Promises。在这一点上,除了代码可读性更强之外,我们还改进了错误处理。只要有一个catch块,我们就不再需要太关注具体的错误捕获。在链接Promises时,catch块捕获会自Promises执行或上一个catch块以来的所有错误。注意,没有catch块的Promises不会终止脚本,但会给你一条可读性较差的消息,比如:

  1. (node:7741) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: something went wrong
  2. (node:7741) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. */

因此,务必要在Promises中加入catch块。

  1. Promise.resolve(1)
  2. .then(res => {
  3. console.log(res) // 1
  4. throw new Error('something went wrong')
  5. return Promise.resolve(2)
  6. })
  7. .then(res => {
  8. console.log(res) // will not get executed
  9. })
  10. .catch(err => {
  11. console.error(err) // we will see what to do with it later
  12. return Promise.resolve(3)
  13. })
  14. .then(res => {
  15. console.log(res) // 3
  16. })
  17. .catch(err => {
  18. // in case in the previous block occurs another error
  19. console.error(err)
  20. })

回到try … catch 

随着JavaScript引入async / await,我们回到了最初的错误处理方法,借助try … catch … finally,错误处理变得非常简单。

因为这和我们处理“普通”同步错误的方法是一样的,所以如果需要的话,更容易使用作用域更大的catch语句。

  1. ;(async function() {
  2. try {
  3. await someFuncThatThrowsAnError()
  4. } catch (err) {
  5. console.error(err) // we will make sense of that later
  6. }
  7. console.log('Easy!') // will get executed
  8. })()

服务器端错误的产生和处理

现在,我们已经有了处理错误的工具,让我们看下,我们在实际情况下能用它们做什么。后端错误的产生和处理是应用程序至关重要的组成部分。对于错误处理,有不同的方法。我将向你展示一个自定义Error构造函数和错误代码的方法,我们可以轻松地传递到前端或任何API消费者。构建后端的细节并不重要,基本思路不变。

我们将使用Express.js作为路由框架。让我们考虑下最有效的错误处理结构。我们希望:

  1. 一般错误处理,如某种回退,基本上只是说:“有错误,请再试一次或联系我们”。这并不是特别聪明,但至少通知用户,有地方错了——而不是无限加载或进行类似地处理。

  2. 特殊错误处理为用户提供详细信息,让用户了解有什么问题以及如何解决它,例如,有信息丢失,数据库中的条目已经存在等等。

构建一个自定义Error构造函数

我们将使用已有的Error构造函数并扩展它。继承在JavaScript中是一件危险的事情,但根据我的经验,在这种情况下,它非常有用。我们为什么需要它?我们仍然希望堆栈跟踪给我们一个很好的调试体验。扩展JavaScript原生Error构造函数可以让我们方便地获得堆栈跟踪。我们唯一要做的是添加代码(我们稍后可以通过错误代码访问)和要传递给前端的状态(http状态代码)。

  1. class CustomError extends Error {
  2. constructor(code = 'GENERIC', status = 500, ...params) {
  3. super(...params)
  4. if (Error.captureStackTrace) {
  5. Error.captureStackTrace(this, CustomError)
  6. }
  7. this.code = code
  8. this.status = status
  9. }
  10. }
  11. module.exports = CustomError

如何处理路由

在完成Error的自定义之后,我们需要设置路由结构。正如我指出的那样,我们想要一个单点真错误处理,就是说,对于每一个路由,我们要有相同的错误处理行为。在默认情况下,由于路由都是封装的,所以Express并不真正支持那种方式。

为了解决这个问题,我们可以实现一个路由处理程序,并把实际的路由逻辑定义为普通的函数。这样,如果路由功能(或任何内部函数)抛出一个错误,它将返回到路由处理程序,然后可以传给前端。当后端发生错误时,我们可以用以下格式传递一个响应给前端——比如一个JSON API:

  1. {
  2. error: 'SOME_ERROR_CODE',
  3. description: 'Something bad happened. Please try again or contact support.'
  4. }

准备好不知所措。当我说下面的话时,我的学生总是生我的气:

如果你咋看之下并不是什么都懂,那没问题。只要使用一段时间,你就会发现为什么要那样。

顺便说一下,这可以称为自上而下的学习,我非常喜欢。

路由处理程序就是这个样子:

  1. const express = require('express')
  2. const router = express.Router()
  3. const CustomError = require('../CustomError')
  4. router.use(async (req, res) => {
  5. try {
  6. const route = require(`.${req.path}`)[req.method]
  7. try {
  8. const result = route(req) // We pass the request to the route function
  9. res.send(result) // We just send to the client what we get returned from the route function
  10. } catch (err) {
  11. /*
  12. This will be entered, if an error occurs inside the route function.
  13. */
  14. if (err instanceof CustomError) {
  15. /*
  16. In case the error has already been handled, we just transform the error
  17. to our return object.
  18. */
  19. return res.status(err.status).send({
  20. error: err.code,
  21. description: err.message,
  22. })
  23. } else {
  24. console.error(err) // For debugging reasons
  25. // It would be an unhandled error, here we can just return our generic error object.
  26. return res.status(500).send({
  27. error: 'GENERIC',
  28. description: 'Something went wrong. Please try again or contact support.',
  29. })
  30. }
  31. }
  32. } catch (err) {
  33. /*
  34. This will be entered, if the require fails, meaning there is either
  35. no file with the name of the request path or no exported function
  36. with the given request method.
  37. */
  38. res.status(404).send({
  39. error: 'NOT_FOUND',
  40. description: 'The resource you tried to access does not exist.',
  41. })
  42. }
  43. })
  44. module.exports = router

我希望你能读下代码中的注释,我认为那比我在这里解释更有意义。现在,让我们看下实际的路由文件是什么样子:

  1. const CustomError = require('../CustomError')
  2. const GET = req => {
  3. // example for success
  4. return { name: 'Rio de Janeiro' }
  5. }
  6. const POST = req => {
  7. // example for unhandled error
  8. throw new Error('Some unexpected error, may also be thrown by a library or the runtime.')
  9. }
  10. const DELETE = req => {
  11. // example for handled error
  12. throw new CustomError('CITY_NOT_FOUND', 404, 'The city you are trying to delete could not be found.')
  13. }
  14. const PATCH = req => {
  15. // example for catching errors and using a CustomError
  16. try {
  17. // something bad happens here
  18. throw new Error('Some internal error')
  19. } catch (err) {
  20. console.error(err) // decide what you want to do here
  21. throw new CustomError(
  22. 'CITY_NOT_EDITABLE',
  23. 400,
  24. 'The city you are trying to edit is not editable.'
  25. )
  26. }
  27. }
  28. module.exports = {
  29. GET,
  30. POST,
  31. DELETE,
  32. PATCH,
  33. }

在这些例子中,我没有做任何有实际要求的事情,我只是假设不同的错误场景。例如,GET /city在第3行结束,POST /city在第8号结束等等。这也适用于查询参数,例如,GET /city?startsWith=R。本质上,你会有一个未处理的错误,前端会收到:

  1. {
  2. error: 'GENERIC',
  3. description: 'Something went wrong. Please try again or contact support.'
  4. }

或者你将手动抛出CustomError,例如:

  1. throw new CustomError('MY_CODE', 400, 'Error description')

上述代码会转换成:

  1. {
  2. error: 'MY_CODE',
  3. description: 'Error description'
  4. }

既然我们有了这个漂亮的后端设置,我们就不会再把错误日志泄漏到前端,而总是返回有用的信息,说明出现了什么问题。

确保你已经在GitHub(https://github.com/gisderdube/graceful-error-handling)上看过完整的库。你可以把它用在任何项目中,并根据自己的需要来修改它!

向用户显示错误

下一个也是最后一个步骤是管理前端的错误。这里,你要使用第一部分描述的工具处理由前端逻辑产生的错误。不过,后端的错误也要显示。首先,让我们看看如何显示错误。如前所述,我们将使用React进行演练。

把错误保存在React状态中

和其他数据一样,错误和错误消息会变化,因此,你想把它们放在组件状态中。在默认情况下,你想要在加载时重置错误,以便用户第一次看到页面时,不会看到错误。

接下来我们必须澄清的是不同错误类型及与其匹配的可视化表示。就像在后端一样,有3种类型:

  1. 全局错误,例如,其中一个常见的错误是来自后端,或者用户没有登录等。

  2. 来自后端的具体错误,例如,用户向后端发送登录凭证。后端答复密码不匹配。前端无法进行此项验证,所以这样的信息只能来自后端。

  3. 由前端导致的具体错误,例如,电子邮件输入验证失败。

2和3非常类似,虽然源头不一样,但如果你愿意,就可以在同样的state中处理。我们将从代码中看下如何实现。

我将使用React的原生state实现,但是,你还可以使用类似MobX或Redux这样的状态管理系统。

全局错误

通常,我将把这些错误保存在最外层的有状态组件中,并渲染一个静态UI元素,这可能是屏幕顶部的一个红色横幅、模态或其他什么东西,设计实现由你决定。

让我们看下代码:

  1. import React, { Component } from 'react'
  2. import GlobalError from './GlobalError'
  3. class Application extends Component {
  4. constructor(props) {
  5. super(props)
  6. this.state = {
  7. error: '',
  8. }
  9. this._resetError = this._resetError.bind(this)
  10. this._setError = this._setError.bind(this)
  11. }
  12. render() {
  13. return (
  14. <div className="container">
  15. <GlobalError error={this.state.error} resetError={this._resetError} />
  16. <h1>Handling Errors</h1>
  17. </div>
  18. )
  19. }
  20. _resetError() {
  21. this.setState({ error: '' })
  22. }
  23. _setError(newError) {
  24. this.setState({ error: newError })
  25. }
  26. }
  27. export default Application

正如你看到的那样,Application.js中的状态存在错误。我们也有方法可以重置并改变错误的值。我们把值和重置方法传递给GlobalError组件,在点击'x'时,该组件会显示错误并重置它。让我们看看GlobalError组件:

  1. import React, { Component } from 'react'
  2. class GlobalError extends Component {
  3. render() {
  4. if (!this.props.error) return null
  5. return (
  6. <div
  7. style={{
  8. position: 'fixed',
  9. top: 0,
  10. left: '50%',
  11. transform: 'translateX(-50%)',
  12. padding: 10,
  13. backgroundColor: '#ffcccc',
  14. boxShadow: '0 3px 25px -10px rgba(0,0,0,0.5)',
  15. display: 'flex',
  16. alignItems: 'center',
  17. }}
  18. >
  19. {this.props.error}
  20. &nbsp;
  21. <i
  22. className="material-icons"
  23. style={{ cursor: 'pointer' }}
  24. onClick={this.props.resetError}
  25. >
  26. close
  27. </i>
  28. </div>
  29. )
  30. }
  31. }
  32. export default GlobalError

你可以看到,在第5行,如果没有错误,我们就不做任何渲染。这可以防止我们的页面上出现一个空的红框。当然,你可以改变这个组件的外观和行为。例如,你可以将“x”替换为Timeout,几秒钟后重置错误状态。

现在,你已经准备好在任何地方使用全局错误状态了,只是从Application.js把_setError向下传递,而且,你可以设置全局错误,例如,当一个请求从后端返回了字段error: 'GENERIC'。例如:

  1. import React, { Component } from 'react'
  2. import axios from 'axios'
  3. class GenericErrorReq extends Component {
  4. constructor(props) {
  5. super(props)
  6. this._callBackend = this._callBackend.bind(this)
  7. }
  8. render() {
  9. return (
  10. <div>
  11. <button onClick={this._callBackend}>Click me to call the backend</button>
  12. </div>
  13. )
  14. }
  15. _callBackend() {
  16. axios
  17. .post('/api/city')
  18. .then(result => {
  19. // do something with it, if the request is successful
  20. })
  21. .catch(err => {
  22. if (err.response.data.error === 'GENERIC') {
  23. this.props.setError(err.response.data.description)
  24. }
  25. })
  26. }
  27. }
  28. export default GenericErrorReq

如果你比较懒,到这里就可以结束了。即使你有具体的错误,你总是可以改变全局错误状态,并把错误提示框显示在页面顶部。不过,我将向你展示如何处理和显示具体的错误。为什么?首先,这是关于错误处理的权威指南,所以我不能停在这里。其次,如果你只是把所有的错误都作为全局错误来显示,那么体验人员会疯掉。

处理具体的请求错误

和全局错误类似,我们也有位于其他组件内部的局部错误状态,过程相同:

  1. import React, { Component } from 'react'
  2. import axios from 'axios'
  3. import InlineError from './InlineError'
  4. class SpecificErrorRequest extends Component {
  5. constructor(props) {
  6. super(props)
  7. this.state = {
  8. error: '',
  9. }
  10. this._callBackend = this._callBackend.bind(this)
  11. }
  12. render() {
  13. return (
  14. <div>
  15. <button onClick={this._callBackend}>Delete your city</button>
  16. <InlineError error={this.state.error} />
  17. </div>
  18. )
  19. }
  20. _callBackend() {
  21. this.setState({
  22. error: '',
  23. })
  24. axios
  25. .delete('/api/city')
  26. .then(result => {
  27. // do something with it, if the request is successful
  28. })
  29. .catch(err => {
  30. if (err.response.data.error === 'GENERIC') {
  31. this.props.setError(err.response.data.description)
  32. } else {
  33. this.setState({
  34. error: err.response.data.description,
  35. })
  36. }
  37. })
  38. }
  39. }
  40. export default SpecificErrorRequest

有件事要记住,清除错误通常有一个不同的触发器。用' x '删除错误是没有意义的。关于这一点,在发出新请求时清除错误会更有意义。你还可以在用户进行更改时清除错误,例如当修改输入值时。

源于前端的错误

如前所述,这些错误可以使用与处理后端具体错误相同的方式(状态)进行处理。这次,我们将使用一个有输入字段的示例,只允许用户在实际提供以下输入时删除一个城市:

  1. import React, { Component } from 'react'
  2. import axios from 'axios'
  3. import InlineError from './InlineError'
  4. class SpecificErrorRequest extends Component {
  5. constructor(props) {
  6. super(props)
  7. this.state = {
  8. error: '',
  9. city: '',
  10. }
  11. this._callBackend = this._callBackend.bind(this)
  12. this._changeCity = this._changeCity.bind(this)
  13. }
  14. render() {
  15. return (
  16. <div>
  17. <input
  18. type="text"
  19. value={this.state.city}
  20. style={{ marginRight: 15 }}
  21. onChange={this._changeCity}
  22. />
  23. <button onClick={this._callBackend}>Delete your city</button>
  24. <InlineError error={this.state.error} />
  25. </div>
  26. )
  27. }
  28. _changeCity(e) {
  29. this.setState({
  30. error: '',
  31. city: e.target.value,
  32. })
  33. }
  34. _validate() {
  35. if (!this.state.city.length) throw new Error('Please provide a city name.')
  36. }
  37. _callBackend() {
  38. this.setState({
  39. error: '',
  40. })
  41. try {
  42. this._validate()
  43. } catch (err) {
  44. return this.setState({ error: err.message })
  45. }
  46. axios
  47. .delete('/api/city')
  48. .then(result => {
  49. // do something with it, if the request is successful
  50. })
  51. .catch(err => {
  52. if (err.response.data.error === 'GENERIC') {
  53. this.props.setError(err.response.data.description)
  54. } else {
  55. this.setState({
  56. error: err.response.data.description,
  57. })
  58. }
  59. })
  60. }
  61. }
  62. export default SpecificErrorRequest

使用错误代码实现错误国际化

也许你一直想知道为什么我们有这些错误代码,例如GENERIC ,我们只是显示从后端传递过来的错误描述。现在,随着你的应用越来越大,你就会希望征服新的市场,并在某个时候面临多种语言支持的问题。如果你到了这个时候,你就可以使用前面提到的错误代码使用用户的语言来显示恰当的描述。

我希望你对如何处理错误有了一些了解。忘掉console.error(err),它现在已经是过去时了。可以使用它进行调试,但它不应该出现在最终的产品构建中。为了防止这种情况,我建议你使用日志库,我过去一直使用loglevel,我对它非常满意。

英文原文

https://levelup.gitconnected.com/the-definite-guide-to-handling-errors-gracefully-in-javascript-58424d9c60e6

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注