原文javascript
接着我上一篇文章,我想谈谈异常。我确定你以前也听过——异常是个好东西。一开始,咱们惧怕异常,毕竟写bug容易被人喷。其实经过修bug,咱们实际上学会了下次开发怎么避免这个bug而且能够作得更好。前端
在生活中,咱们常说吃一堑长一智。但对于打代码来讲,有些不同。咱们的编译器和一些工具如今都很智能,不但告诉咱们哪里出错,还帮助咱们优化代码【译者:eslint之类的】(有可能还会教咱们如何修复bug)。java
throw new Error('something went wrong')
以上代码将会建立异常实例并中止执行你的脚本,除非你在错误回调里作一些处理。当你开始了js开发者的职业生涯,你本身极可能不会这样作,可是你会在其它的库里(或者运行时)看到相似‘ReferenceError: fs为定义’这样的错误。node
异常对象有两个属性供咱们使用。第一个是message,是你传递给异常的构造函数的参数,好比:react
new Error('This is the message')
你可使用message属性来访问到该消息:ios
const myError = new Error(‘please improve your code’) console.log(myError.message) // please improve your code
第二个参数是异常堆栈跟踪,很是重要。你可使用stack属性来访问。异常堆栈为你提供历史记录(调用堆栈),从中能够查看到哪些文件致使了异常。堆栈顶部也包括了消息,而后是实际的堆栈,从距离异常最近的点开始,而后一直到最外层与异常有关的文件(译者:调用关系的追溯):git
Error: please improve your code at Object.<anonymous> (/Users/gisderdube/Documents/_projects/hacking.nosync/error-handling/src/general.js:1:79) at Module._compile (internal/modules/cjs/loader.js:689:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10) at Module.load (internal/modules/cjs/loader.js:599:32) at tryModuleLoad (internal/modules/cjs/loader.js:538:12) at Function.Module._load (internal/modules/cjs/loader.js:530:3) at Function.Module.runMain (internal/modules/cjs/loader.js:742:12) at startup (internal/bootstrap/node.js:266:19) at bootstrapNodeJSCore (internal/bootstrap/node.js:596:3)
如今单个异常实例没有任何卵用。例如express
new Error('...')
以上代码并不会触发任何东西。当异常被抛出,事情就变得有趣了一些。而后,跟上文说的同样,js引擎中止执行你的脚本,除非你作了异常处理。记住,手动抛出异常,仍是由库抛出异常,抑或是运行时抛出异常,都不要紧。让咱们看看在不一样场景如何处理这些异常。bootstrap
这是最简单的,可是常常被忘记的异常处理方法——多亏了async/await,愈来愈多人使用它了。它能够用来捕捉各类类型的非异步错误。例如:axios
const a = 5 try { console.log(b) // b is not defined, so throws an error } catch (err) { console.error(err) // will log the error with the error stack } console.log(a) // still gets executed
若是咱们不将console.log(b)包装在try ... catch块中,脚本执行将中止。
有时候有无论有没有异常,都但愿执行的代码。你可使用finally。一般,它与try ... catch语句以后只有一行相同,但有时它可能颇有用
const a = 5 try { console.log(b) // b is not defined, so throws an error } catch (err) { console.error(err) // will log the error with the error stack } finally { console.log(a) // will always get executed }
异步,这是你在使用js时不得不去考虑的一个主题。当你有个异步方法,而且改方法内部发生异常时,你的脚本会继续执行,不会当即出现任何异常。当使用回调来处理异步方法的返回时(顺便提一下,不提倡使用回调),你一般会接收两个参数,例如:
myAsyncFunc(someInput, (err, result) => { if(err) return console.error(err) // we will see later what to do with the error object. console.log(result) })
若是发生异常,err参数就是那个异常。若是没有,参数就是undefined或者时null。这样作很重要,否则若是你试图访问result.data时,乳沟发生异常,获得的结果就是undefined。
处理异步的另外一种方法时使用promises。除了代码更易读,异常处理也改进了。咱们只须要在catch里处理异常就行了,不须要关心怎么捕捉异常。当链式调用promises时,catch会捕获自promise或最后一个catch块执行以来的全部错误。请注意,没有catch的promises不会终止脚本,可是会下降你的异常信息的可读性:
(node:7741) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: something went wrong (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:
Promise.resolve(1) .then(res => { console.log(res) // 1 throw new Error('something went wrong') return Promise.resolve(2) }) .then(res => { console.log(res) // will not get executed }) .catch(err => { console.error(err) // we will see what to do with it later return Promise.resolve(3) }) .then(res => { console.log(res) // 3 }) .catch(err => { // in case in the previous block occurs another error console.error(err) })
随着js引入async / await,咱们回到了处理异常的原始方式,使用try ... catch ... finally,这使得处理它们变得垂手可得:
;(async function() { try { await someFuncThatThrowsAnError() } catch (err) { console.error(err) // we will make sense of that later } console.log('Easy!') // will get executed })()
因为这和咱们处理“普通”同步异常方式同样,因此若是有须要,更容易使用更大做用域的catch语句。
如今咱们有处理异常的工具了,让咱们看看在实际状况中能够用这些工具作些什么。异常产生后能在后端正确处理是app的关键部分。这列有几种处理异常的方法。我将向你展现自定义error构造函数和错误代码的方法,咱们能够轻松地将其传递给前端或任何API调用者。构建后端的细节不重要,基本思路不变。
咱们用Express.js做为路由框架。让咱们考虑一下咱们但愿得到最有效的异常处理的结构。咱们想要:
咱们使用存在的erroe构造函数而且继承它。继承在js中是一件危险的事,可是在这里,我以为很是有用。为何咱们须要它?咱们仍然但愿堆栈跟踪为咱们提供良好的调试体验。拓展js自带的error构造函数就能够继续使用堆栈跟踪。咱们惟一要作的就是添加代码和传递前端error.code
class CustomError extends Error { constructor(code = 'GENERIC', status = 500, ...params) { super(...params) if (Error.captureStackTrace) { Error.captureStackTrace(this, CustomError) } this.code = code this.status = status } } module.exports = CustomError
完成error的自定义以后,咱们须要设置路由结构。正如我所指出的,咱们须要一个单点truth来进行异常处理,这意味着对于每一个路由,咱们都但愿具备相同的异常处理行为。express默认是不支持的,由于路由封装好了。
为了解决这个问题,咱们能够实现一个路由处理程序,并把实际的路由逻辑定义为普通函数。这样,若是路由功能(或任何内部函数)抛出异常,他将返回到路由处理程序,而后能够返回给前端。当后端发生错误时,咱们用如下格式传递给前端——好比一个JSON API:
{ error: 'SOME_ERROR_CODE', description: 'Something bad happened. Please try again or contact support.' }
准备好大吃一惊吧,当我说下面这段话时,个人学生老是生气:
若是你咋看之下不太理解,不用担忧。只要使用一段时间,你就会发现为何要那样。
顺便说一下,这叫自上而下学习,我很是喜欢。
路由处理程序像这样子:
const express = require('express') const router = express.Router() const CustomError = require('../CustomError') router.use(async (req, res) => { try { const route = require(`.${req.path}`)[req.method] try { const result = route(req) // We pass the request to the route function res.send(result) // We just send to the client what we get returned from the route function } catch (err) { /* This will be entered, if an error occurs inside the route function. */ if (err instanceof CustomError) { /* In case the error has already been handled, we just transform the error to our return object. */ return res.status(err.status).send({ error: err.code, description: err.message, }) } else { console.error(err) // For debugging reasons // It would be an unhandled error, here we can just return our generic error object. return res.status(500).send({ error: 'GENERIC', description: 'Something went wrong. Please try again or contact support.', }) } } } catch (err) { /* This will be entered, if the require fails, meaning there is either no file with the name of the request path or no exported function with the given request method. */ res.status(404).send({ error: 'NOT_FOUND', description: 'The resource you tried to access does not exist.', }) } }) module.exports = router
我但愿你看下代码的注释,我想这比我在这解释有意义。如今,让咱们看下实际的路由文件长什么样子:
const CustomError = require('../CustomError') const GET = req => { // example for success return { name: 'Rio de Janeiro' } } const POST = req => { // example for unhandled error throw new Error('Some unexpected error, may also be thrown by a library or the runtime.') } const DELETE = req => { // example for handled error throw new CustomError('CITY_NOT_FOUND', 404, 'The city you are trying to delete could not be found.') } const PATCH = req => { // example for catching errors and using a CustomError try { // something bad happens here throw new Error('Some internal error') } catch (err) { console.error(err) // decide what you want to do here throw new CustomError( 'CITY_NOT_EDITABLE', 400, 'The city you are trying to edit is not editable.' ) } } module.exports = { GET, POST, DELETE, PATCH, }
在这些例子中,我没有对实际请求作任何事情,我只是伪装不一样的异常场景。 所以,例如,GET / city将在第3行结束,POST / city将在第8行结束,依此类推。 这也适用于查询参数,例如 GET / city?startsWith = R. 从本质上讲,您将有一个未处理的异常,前端将收到:
{ error: 'GENERIC', description: 'Something went wrong. Please try again or contact support.' }
或者你手动抛出CustomError,例如:
throw new CustomError('MY_CODE', 400, 'Error description')
上述代码会变成:
{ error: 'GENERIC', description: 'Something went wrong. Please try again or contact support.' }
如今咱们有了这个漂亮的后端设置,咱们再也不有错误日志泄漏到前端,并将始终返回有关出错的可用信息。
下一步也是最后一步是管理前端的异常。 在这里,您但愿使用第一部分中描述的工具处理前端逻辑自己产生的异常。可是,也必须显示来自后端的异常。 咱们先来看看咱们如何显示异常。 如前所述,咱们将在演练中使用React。
接下来咱们要澄清的是具备匹配视觉表示的不一样类型的异常。就像在后端同样,有三种类型:
2和3虽然源头不同,可是很是相似而且能够在一样的state处理。咱们来看看在代码中如何实现。
咱们使用react原声state实现,可是,你可使用相似MobX或Redux这样的状态管理系统。
一般,我将这些异常保存在最外层的有状态组件中并呈现静态UI元素,这多是屏幕顶部的红色横幅,模态或其余任何内容,设计实现你本身决定。
来看下代码:
import React, { Component } from 'react' import GlobalError from './GlobalError' class Application extends Component { constructor(props) { super(props) this.state = { error: '', } this._resetError = this._resetError.bind(this) this._setError = this._setError.bind(this) } render() { return ( <div className="container"> <GlobalError error={this.state.error} resetError={this._resetError} /> <h1>Handling Errors</h1> </div> ) } _resetError() { this.setState({ error: '' }) } _setError(newError) { this.setState({ error: newError }) } } export default Application
正如你所看到的同样,Application.js中的状态存在异常。咱们也有方法重置和更改异常值。 咱们将值和重置方法传递给GlobalError
组件,在点击‘x’时,该组件会显示异常并重置。让咱们来看看 咱们将值和reset方法向下传递给GlobalError
组件:
import React, { Component } from 'react' class GlobalError extends Component { render() { if (!this.props.error) return null return ( <div style={{ position: 'fixed', top: 0, left: '50%', transform: 'translateX(-50%)', padding: 10, backgroundColor: '#ffcccc', boxShadow: '0 3px 25px -10px rgba(0,0,0,0.5)', display: 'flex', alignItems: 'center', }} > {this.props.error} <i className="material-icons" style={{ cursor: 'pointer' }} onClick={this.props.resetError} > close </i> </div> ) } } export default GlobalError
你能够在第五行看到,若是没有异常,咱们不会渲染任何内容。这能够防止咱们始终在页面上显示空的红色框。固然,你能够更改此组件的外观和行为。例如,你可使用Timeout替换'x',以便在几秒钟后重置异常状态。
如今,你已准备好在任何地方使用此全局异常状态,只需从Application.js传递_setError,而后就能够设置全局异常,例如 当来自后端的请求返回时出现字段error:'GENERIC'。例如:
import React, { Component } from 'react' import axios from 'axios' class GenericErrorReq extends Component { constructor(props) { super(props) this._callBackend = this._callBackend.bind(this) } render() { return ( <div> <button onClick={this._callBackend}>Click me to call the backend</button> </div> ) } _callBackend() { axios .post('/api/city') .then(result => { // do something with it, if the request is successful }) .catch(err => { if (err.response.data.error === 'GENERIC') { this.props.setError(err.response.data.description) } }) } } export default GenericErrorReq
若是你很懒,你能够在这里停下来。即便你有具体异常,也能够随时更改全局异常状态并在页面顶部显示错误框。可是,本文展现如何处理和显示特定的异常。为何?首先,这是处理异常的指南,因此我不能就此止步。其次,若是你把全部异常都做为全局状态来显示,那么UX人员会感到很难受。
与全局异常相似,咱们也能够在其余组件中包含局部异常状态。 程序是同样的:
import React, { Component } from 'react' import axios from 'axios' import InlineError from './InlineError' class SpecificErrorRequest extends Component { constructor(props) { super(props) this.state = { error: '', } this._callBackend = this._callBackend.bind(this) } render() { return ( <div> <button onClick={this._callBackend}>Delete your city</button> <InlineError error={this.state.error} /> </div> ) } _callBackend() { this.setState({ error: '', }) axios .delete('/api/city') .then(result => { // do something with it, if the request is successful }) .catch(err => { if (err.response.data.error === 'GENERIC') { this.props.setError(err.response.data.description) } else { this.setState({ error: err.response.data.description, }) } }) } } export default SpecificErrorRequest
这里要记住的一件事,清除异常一般会有不一样的触发器。 使用'x'删除异常是没有意义的。在这里,在发出新请求时清除异常会更有意义。你还能够在用户进行更改时清除异常,例如,当输入值改变时。
如前所述,这些异常能够与来自后端的特定异常以相同的方式(状态)处理。 我此次使用带有输入字段的示例,只容许用户删除城市,当他实际提供输入时:
import React, { Component } from 'react' import axios from 'axios' import InlineError from './InlineError' class SpecificErrorRequest extends Component { constructor(props) { super(props) this.state = { error: '', city: '', } this._callBackend = this._callBackend.bind(this) this._changeCity = this._changeCity.bind(this) } render() { return ( <div> <input type="text" value={this.state.city} style={{ marginRight: 15 }} onChange={this._changeCity} /> <button onClick={this._callBackend}>Delete your city</button> <InlineError error={this.state.error} /> </div> ) } _changeCity(e) { this.setState({ error: '', city: e.target.value, }) } _validate() { if (!this.state.city.length) throw new Error('Please provide a city name.') } _callBackend() { this.setState({ error: '', }) try { this._validate() } catch (err) { return this.setState({ error: err.message }) } axios .delete('/api/city') .then(result => { // do something with it, if the request is successful }) .catch(err => { if (err.response.data.error === 'GENERIC') { this.props.setError(err.response.data.description) } else { this.setState({ error: err.response.data.description, }) } }) } } export default SpecificErrorRequest
我但愿你对如何处理异常有所了解。忘记console.error(错误),它是过去的事情了。 可使用它进行调试,但它不该该在生产版本中。 为了防止这种状况,我建议你使用一个日志库,我过去一直在使用loglevel,我很满意。