你最好的选择是throw
an Error
包装该值,这会导致拒绝的承诺Error
包装值:
} catch (error) {
throw new Error(400);
}
你也可以只throw
值,但没有堆栈跟踪信息:
} catch (error) {
throw 400;
}
或者,返回一个被拒绝的承诺Error
包装该值,但这不是惯用的:
} catch (error) {
return Promise.reject(new Error(400));
}
(要不就return Promise.reject(400);
,但同样,没有上下文信息。)
在你的情况下,当你使用TypeScript
and foo
的返回值为Promise<A>
,你会用这个:
return Promise.reject<A>(400 /*or Error*/ );
In an async
/await
在这种情况下,最后一个可能有点语义不匹配,但它确实有效。
如果你抛出一个Error
,这与任何消耗你的东西都能很好地配合foo
的结果是await
syntax:
try {
await foo();
} catch (error) {
// Here, `error` would be an `Error` (with stack trace, etc.).
// Whereas if you used `throw 400`, it would just be `400`.
}