简体   繁体   中英

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
}

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!

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.

Flow doesn't support checked exceptions. It makes no attempt to model which functions may throw or what sorts of errors they may throw.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM