【知识整理】Node.js-Koa之错误处理

一。错误处理

1.500错误:如代码运行过程发生错误,我们需要把错误信息返回给用户。HTTP协议规定这时要返回500状态吗,koa提供了ctx.throw()方法,用来抛出错误。

const main = ctx =>{
	ctx.throw(500);
}
2.404错误:如将ctx.response.status设置成404,相当于ctx.thow(404),返回404错误

const main = ctx =>{
	ctx.response.status = 404;
	ctx.response.body = 'Page Not Fo..und';
}
3.处理错误的中间件:为方便处理错误,最好用try-catch将其捕获,但每个中间件都这么写就很麻烦,可以让最外层的中间件负责所有中间件的错误处理。

const handler = async (ctx, next) =>{
	try{
		await next();
	}catch(e){
		ctx.response.status = e.statusCode ||e.status ||500;
	}
}
const main = ctx =>{
	ctx.throw(500);
}
app.use(handler);
app.use(main);
4.error事件监听:运行过程中出错,koa会触发一个error事件。监听该事件,可以处理错误。

const main = ctx =>{
	ctx.throw(500);
};
app.on('error', (err, ctx) =>{
	console.error(err);
})
5.释放error事件:如果错误被try-catch捕获,就不触发error事件,这时必须调用ctx.app.emit(),手动释放error事件,才能让监听函数生效

const handler = async (ctx, next) =>{
	try{
		await next();
	}catch(err){
		ctx.respose.status = err.statusCode ||err. status || 500;
		ctx.response.type = 'html';
		ctx.response.body = '<p>出错啦</p>';
		ctx.app.emit('error', err, ctx);
	}
}
ctx.main = ctx =>{
	ctx.throw(500);
}
app.on('error', function(err){
	console.log(err);
})






猜你喜欢

转载自blog.csdn.net/qq_19891827/article/details/78666494