Your best bet is to throw
an Error
wrapping the value, which results in a rejected promise with an Error
wrapping the value:(你最好的办法是throw
一个Error
包装值,这会导致一个被拒绝的承诺,并包含一个Error
值:)
} catch (error) {
throw new Error(400);
}
You can also just throw
the value, but then there's no stack trace information:(您也可以throw
值,但是没有堆栈跟踪信息:)
} catch (error) {
throw 400;
}
Alternately, return a rejected promise with an Error
wrapping the value:(或者,返回一个被拒绝的promise,其中包含一个Error
:)
} catch (error) {
return Promise.reject(new Error(400));
}
(Or just return Promise.reject(400);
, but again, then there's no context information.)((或者只return Promise.reject(400);
但是,再次,那么没有上下文信息。))
(In your case, as you're using TypeScript
and foo
's retrn value is Promise<A>
, you'd use return Promise.reject<A>(400 /*or error*/);
)((在你的情况下,当你使用TypeScript
和foo
的retrn值是Promise<A>
,你会使用return Promise.reject<A>(400 /*or error*/);
))
In an async
/ await
situation, that last is probably a bit of a semantic mis-match, but it does work.(在async
/ await
情况下,最后一个可能是语义不匹配,但确实有效。)
If you throw an Error
, that plays well with anything consuming your foo
's result with await
syntax:(如果你抛出一个Error
,那么使用await
语法消耗foo
结果的任何东西都能很好地运行:)
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`.
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…