Open onvno opened 5 years ago
try {
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
}).then((res) => {
console.log(res)
}).catch(err => {
console.log("errr:", err)
// err catch后就不会throw,下边代码不生效
throw err
})
} catch (error) {
// promise此处不会触发
console.log('eeee')
throw error
}
app.use(async (ctx, next) => {
try {
await next();
} catch (err) {
ctx.status = err.status || 500;
ctx.body = err.message;
ctx.app.emit('error', err, ctx);
}
});
app.on('error', (err, ctx) => {
/* centralized error handling:
* console.log error
* write error to log file
* save error and request information to database if ctx.request match condition
* ...
*/
});
除了少数例外,同步的 API(任何不接受 callback 函数的阻塞方法,例如 fs.readFileSync)会使用 throw 报告错误。
异步的 API 中发生的错误可能会以多种方式进行报告:
const fs = require('fs');
fs.readFile('一个不存在的文件', (err, data) => {
if (err) {
console.error('读取文件出错!', err);
return;
}
// 否则处理数据
});
const net = require('net');
const connection = net.connect('localhost');
// 添加一个 'error' 事件句柄到一个流: connection.on('error', (err) => { // 如果连接被服务器重置,或无法连接,或发生任何错误,则错误会被发送到这里。 console.error(err); });
connection.pipe(process.stdout);
* Node.js API 中有一小部分普通的异步方法仍可能使用 throw 机制抛出异常,且必须使用 try / catch 处理。 这些方法并没有一个完整的列表;请参阅各个方法的文档以确定所需的合适的错误处理机制。
'error' 事件机制的使用常见于基于流和基于事件触发器的 API,它们本身就代表了一系列的异步操作(相对于要么成功要么失败的单一操作)。
对于所有的 EventEmitter 对象,如果没有提供一个 'error' 事件句柄,则错误会被抛出,并造成 Node.js 进程报告一个未处理的异常且随即崩溃,除非: 适当地使用 domain 模块或已经注册了一个 [process.on('uncaughtException')] 事件的句柄。
const EventEmitter = require('events'); const ee = new EventEmitter();
setImmediate(() => { // 这会使进程崩溃,因为还为添加 'error' 事件句柄。 ee.emit('error', new Error('这会崩溃')); });
这种方式产生的错误无法使用 try / catch 截获,因为它们是在调用的代码已经退出后抛出的。
开发者必须查阅各个方法的文档以明确在错误发生时这些方法是如何冒泡的。
Node稳定性的研究心得:司徒正美
只要给uncaughtException配置了回调,Node进程不会异常退出,但异常发生的上下文已经丢失,我们无法给出友好的返回,比如告诉用户哪里出问题了。而且由于uncaughtException事件发生后,会丢失当前环境的堆栈,可能导致Node不能正常进行内存回收,从而导致内存泄露。所以,uncaughtException的正确使用姿势是,当uncaughtException触发,记录error日志,然后结束Node进程,我们通过日志监控,报警及时解决异常。
try..catch的同步写法很难受,所以有开发者写了一篇文章探讨How to write async await without try-catch blocks in Javascript,实现了类似Go的同步写法
import to from './to.js';
async function asyncTask() {
let err, user, savedTask;
[err, user] = await to(UserModel.findById(1));
if(!user) throw new CustomerError('No user found');
[err, savedTask] = await to(TaskModel({userId: user.id, name: 'Demo Task'}));
if(err) throw new CustomError('Error occurred while saving task');
if(user.notificationsEnabled) {
const [err] = await to(NotificationService.sendNotification(user.id, 'Task Created'));
if (err) console.error('Just log the error and continue flow');
}
}
原本的写法:
async function asyncTask(cb) {
try {
const user = await UserModel.findById(1);
if(!user) return cb('No user found');
} catch(e) {
return cb('Unexpected error occurred');
}
try {
const savedTask = await TaskModel({userId: user.id, name: 'Demo Task'});
} catch(e) {
return cb('Error occurred while saving task');
}
if(user.notificationsEnabled) {
try {
await NotificationService.sendNotification(user.id, 'Task Created');
} catch(e) {
return cb('Error while sending notification');
}
}
if(savedTask.assignedUser.id !== user.id) {
try {
await NotificationService.sendNotification(savedTask.assignedUser.id, 'Task was created for you');
} catch(e) {
return cb('Error while sending notification');
}
}
cb(null, savedTask);
}
作者的库:await-to-js
针对错误的返回,bluebird提供了Promise.try
,通过链式catch到错误
bluebird与原生Promise对象及bluebird模块的中文API文档
从不用 try-catch 实现的 async/await 语法说错误处理 作者使用try,catch做了封装,没有具体看完