Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 759
ThomasReggi Avatar asked Dec 29 '25 07:12

ThomasReggi


2 Answers

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.

like image 151
Gabriele Petronella Avatar answered Dec 30 '25 20:12

Gabriele Petronella


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

like image 24
Nat Mote Avatar answered Dec 30 '25 21:12

Nat Mote



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!