Koa.js 错误处理
错误处理在构建 Web 应用程序中起着重要作用。 Koa 也为此使用了中间件。
在 Koa 中,您添加了一个将
try { 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: Error Message
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/learning/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
现在任何发送到服务器的请求都会导致这个错误。