错误处理在构建Web应用程序中起着重要作用. Koa也为此目的使用中间件.
在Koa中,您添加了一个中间件尝试{yield next} 作为第一个中间件之一.如果我们在下游遇到任何错误,我们将返回相关的catch子句并在此处理错误.例如 :
var koa = require('koa'); var app = koa(); //Error handling middleware app.use(function *(next) { try { yield next; } catch (err) { this.status = err.status || 500; this.body = err.message; this.app.emit('error', err, this); } }); //Create an error in the next middleware //Set the error message and status code and throw it using context object app.use(function *(next) { //This will set status and message this.throw('Error Message', 500); }); app.listen(3000);
我们故意在上面的代码中创建了一个错误,并在我们的第一个中间件的catch块中处理错误.然后将其发送到我们的控制台,并作为响应发送给我们的客户端.以下是我们触发此错误时收到的错误消息.
InternalServerError:错误消息 at Object.module.exports.throw (/home/ayushgp/learning/koa.js/node_modules/koa/lib/context.js:91:23) at Object.< anonymous> (/home/ayushgp/learning/koa.js/error.js:18:13) at next(native) at onFulfilled(/home/ayushgp/learning/koa.js/node_modules/co)/index.js:65:19) at/home/ayushgp/learning/koa.js/node_modules/co/index.js:54:5 at Object.co(/home/ayushgp/学习/koa.js/node_modules/co/index.js:50:10) at Object.toPromise(/home/ayushgp/learning/koa.js/node_modules/co/index.js:118:63) at next(/home/ayushgp/learning/koa.js/node_modules/co/index.js:99:29) at onFulfilled(/home/ayushgp/learning/koa.js/node_modules/co/index.js:69:7) at/home/ayushgp/learning/koa.js/node_modules/co/index.js:54:5
现在发送到服务器的任何请求都会导致此错误.