ThomasReggi
ThomasReggi

Reputation: 59345

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
}

Upvotes: 2

Views: 1749

Answers (2)

Gabriele Petronella
Gabriele Petronella

Reputation: 108101

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.

Upvotes: 4

Nat Mote
Nat Mote

Reputation: 4086

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

Upvotes: 1

Related Questions