CNode

node async await 怎么捕获错误呢

问答
Ggwyy发布于9 年前最后回复9 年前14 回复8397 浏览0 收藏

我知道是用 reject来抛出错误,但是 如果 在一个大大的try catch里面 有很多普通函数 怎么抛出异常呢

比如说

async function insert(id) { if(id == 6) { return new Promise((resolve,reject) => {reject("aaa")}); } await db.insert(); //something... } (async () =>{ try { await insert(6); } catch(e) { res.end({error:true,msg:e}); } })();

上面就是一个简单的 判断id的函数 没有复杂的 异步 但是如果这个函数出问题了 要new一个promise来返回错误吗 还是像这样

async function insert(id) { return new Promise( (resolve,reject) => { if(id == 6) { return reject("aaa"); } await db.insert(); //something... } ); }

把函数所有的代码都 包到一个大大的 primise里面 ?

查看回复

回复 (14)

H
h87kg#1·9 年前
async function insert(id) {
	if(id == 6) {
		return Promise.reject(“aaa”);
	}
	await db.insert();
	//something…
}
H
h87kg#2·9 年前
const { reject } = Promise
async function insert(id) {
	if(id == 6) {
		return reject(“aaa”);
	}
	await db.insert();
	//something…
}
B
burning0xb#3·9 年前

哥哥 既然try catch了 出错就throw new Error();既可以了

G
gwyy#4·9 年前
引用 burning0xb哥哥 既然try catch了 出错就throw new Error();既可以了

@burning0xb 大哥 不能 throw new Error啊 如果抛出error代码直接就崩溃了

R
rrbe#7·9 年前

在最外层 try catch,里面 throw 的错误会冒泡被捕获到,再做处理就好了

N
nnliang#8·9 年前
...
catch(err) {
	next(err)
}
G
gwyy#10·9 年前
引用 burning0xb@gwyy catch住怎么会崩溃

@burning0xb 真的 catch住 throw new Error 也会崩溃

B
burning0xb#11·9 年前
引用 gwyy@burning0xb 真的 catch住 throw new Error 也会崩溃

@gwyy

不是很明白你说的,不过我这样是没问题的

class App {

  constructor() {
    this.num = 0;
    const method = Object.getOwnPropertyNames(App.prototype);
    method.map((key) => {
      if (key !== 'constructor' && key !== 'bindMethod') {
        this[key] = App.prototype[key].bind(this);
      }
    });
  }

  async _catch() {
    this.num++;
    if (this.num < 6) {
      await this._catch();
    } else {
      throw new Error('exception');
    }
  }

  async __main__() {
    try {
      await this._catch();
    } catch (err) {
      console.log(err);
      console.log('I catch it');
    }
    setInterval(() => {
      console.log('hi');
    }, 3000)
  }

}

const app = new App();

app.__main__();

WechatIMG415.jpeg

Z
ZongDuCha#12·9 年前

zan

S
sunzhiguang#14·9 年前

参考lodash的 attempt exports.attempt = function (promiseFn, ...args) { return promiseFn.apply(null, args).then( function (result) { return result; }, function (e) { return _.isError(e) ? e : new Error(e); } ).catch(function (e) { return e; }); };

使用 let result = await attempt(promisefn, arguments); 判断 result 是不是error _.isError(result); 我是这样处理的

参与回复
登录后即可参与回复。登录