Flow: Flow can't type the error in try/catch block

Created on 10 Apr 2017  路  5Comments  路  Source: facebook/flow

I'm using flow-coverage-report, and it enlightened me to the fact that we can't type try/catch blocks. I've tried looking everywhere for documentation on try/catch and Flow, but couldn't find a thing.

This is a problem if I'm going to use the error to update my Redux store, for example.

This kind of typing doesn't help with coverage:

const result: MessageType | Error = (rawMessage) => {
  try { 
    return JSON.parse(rawMessage);
  } catch(e) {
    return e;
  }
};

Additionally, I tried to type the caught error (in most cases, I know which types of errors are possible), but this is a syntax error, unexpected token:

type ParseError = { [ error properties here ] };
try { 
    return JSON.parse(rawMessage);
  } catch(e: ParseError) {
    return e;
  }

Wondering if there is a plan for adding try/catch typing for Flow, or if there are other approaches I could take. Thank you!

Most helpful comment

@nmn this is not about type-safety, this is about not being able to get 100% coverage

All 5 comments

There is no workaround at the moment. See https://github.com/facebook/flow/pull/3259

Well you could always use type-casting.

In the long-term I can only see two ways to solve this:

  1. Adding a whole new system for errors in Flow. This would probably look something like the throws syntax from swift.

This would mean that JSON.parse would have a type that looks like this:

declare var JSON: {
  parse(str: string): mixed throws ParseError;
}

This would make the code way more type-safe and force you to always check for uncaught errors. However, this would also push developers into relying on throwing exceptions.

My recommendation would be to...

  1. Avoid run-time errors as much as possible and use alternate return values instead.

This would mean that other than in built-in function, your code should avoid ever throwing anything. Instead you functions should return union types of Value | Error.

This is a much better approach as you get the same type safety benefits without sacrificing performance by using try-catch.

That is great news - looking forward to the update. Thanks!

@nmn this is not about type-safety, this is about not being able to get 100% coverage

@vkurchatkin agreed - i just ran into the same thing as i started upon the path of 100% coverage :(

image

grrr :-P

Was this page helpful?
0 / 5 - 0 ratings

Related issues

xtinec picture xtinec  路  65Comments

sophiebits picture sophiebits  路  66Comments

jamesisaac picture jamesisaac  路  44Comments

NgoKnows picture NgoKnows  路  40Comments

jlongster picture jlongster  路  55Comments