16- node.js中try-catch与异步操作

异步操作通过 try-catch 捕获异常
虽然结果输出ok 但是无法写入成功

var fs=require('fs')

try{
    fs.writeFile('./xxxx/abc.txt','666','utf8',function (err) {
       console.log('ok')
    })

}catch(e){
    console.log('出错了'+e)
}

通过错误号 err抛出异常

var fs=require('fs')

fs.writeFile('./xxxx/abc.txt','大家好','utf8',function (err) {
    if(err){
        console.log('出错了')
        throw err;  /!* 通过错误号 err抛出异常 *!/
    }else {
        console.log('ok')
    }
})

猜你喜欢

转载自blog.csdn.net/MDZZ___/article/details/91378325