Flowtype函数会引发错误 [英] Flowtype function can throw error
问题描述
是否有任何方法可以定义一个函数可以明确抛出的错误,显然任何函数都可以抛出错误.但是我想明确定义一个函数旨在引发并且可能根本不返回值.
Is there any way to define that a function explicitly can throw, obviously any function can throw an error. But I'd like to explicitly define that a function is designed to throw and possibly not return a value at all.
async function falseThrow (promise: Promise<any>, error): any {
let value: any = await promise
if (!value) throw error
return value
}
推荐答案
正如Nat Mote在她的回答中强调的那样,无法对流中的检查异常进行编码.
As Nat Mote highlighted in her answer, there's no way of encoding checked exceptions in flow.
但是,如果您愿意稍微更改编码,则可以做一些等效的事情:
However, if you're open to change the encoding a bit, you could do something equivalent:
async function mayFail<A, E>(promise: Promise<?A>, error: E): E | A {
let value = await promise
if (!value) {
return error
}
return value
}
现在流程将迫使用户处理错误:
Now flow will force the user to handle the error:
const p = Promise.resolve("foo")
const result = await mayFail(p, Error("something went wrong"))
if (result instanceof Error) {
// handle the error here
} else {
// use the value here
result.trim()
}
如果您尝试做类似的事情
If you try to do something like
const p = Promise.resolve("foo")
const result = await mayFail(p, Error("something went wrong"))
result.trim() // ERROR!
流程会阻止您,因为您尚未检查result
是Error
还是string
,因此调用trim
不是安全的操作.
flow will stop you, because you haven't checked whether result
is an Error
or a string
, so calling trim
is not a safe operation.
这篇关于Flowtype函数会引发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!