开发手册 欢迎您!
软件开发者资料库

Koa.js - 错误处理

Koa.js错误处理 - 从简单和简单的步骤学习Koa.js,从基本到高级概念,包括概述,环境,Hello World,生成器,路由,URL构建,HTTP方法,请求对象,响应对象,重定向,错误处理,级联,表单数据,文件上传,模板,静态文件,Cookie,会话,身份验证,压缩,缓存,数据库,RESTful API,日志记录,脚手架,资源。

错误处理在构建Web应用程序中起着重要作用. Koa也为此目的使用中间件.

在Koa中,您添加了一个中间件尝试{yield next} 作为第一个中间件之一.如果我们在下游遇到任何错误,我们将返回相关的catch子句并在此处理错误.例如 :

var koa = require('koa');var app = koa();//Error handling middlewareapp.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 objectapp.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

现在发送到服务器的任何请求都会导致此错误.