4 ms·
I'm interested in the way you describe handling errors here. Do you have any real world examples you can point me to? Thanks
by dkdbejwi383 7y ago
I'm interested in the way you describe handling errors here. Do you have any real world examples you can point me to? Thanks
- nesarkvechnep 7y agoCheck out the Either monad in Haskell. It has an implementation in the JS library funfix.
- valand 7y agoI would have gladly shown it to you, but almost all my code is proprietary Here's a small example: ``` function fetchCurrentWeather(){ return fetch(...) .catch(() => ({ error: new NetworkError(), value: null}) .then(res => res.json()) .then(maybeWeather => Weather.is(maybeWeather) ? { value: maybeWeather, error: null} : { error: new DecodeError(), value: null}) .catch(() => ({ error: new DecodeError(), value: null})) } // And then you use it somewhere in you react app async initialFetch(){ try { if (this.state.isLoading) return; this.setState({ isLoading: true, weather: null, error: null }); this.setState({ weather: await fetchCurrentWeather().then(reault => { if (result.error) throw result.error; return result.value; }) }); } catch (error) { this.setState({ error }) } finally { this.setState({ isLoading: false }); } } render(){ return ( <div> {this.state.isLoading && ...} {this.state.weather && ...} {this.state.error && ...} </div> ) } ```
- valand 7y agoDarn, sorry for the bad format. Typing this from phone. I guess you gotta copy that to your editor and apply some formatter.
- pdyck 7y agoWhy is this better than throwing errors or using Promise.resolve()? I know it is inefficient because creating a new error with a stack trace each time is bad for performance. However, you can also throw errors which do not extend Error to avoid this. Destructuring the output and explicitly checking for errors every time seems to be quite the hassle.
- threatofrain 7y agoSeems quite like Go.
- JamesSwift 7y agoBecause the error/success is encoded in the type, you are forced to handle the error case. If you aren't also wrapping throwable functions in `try/catch` then you have a lot of unhandled error cases. If you know that something truly isn't going to error then you can just force cast it as `foo as Success<T>`. That will still blow up at runtime if its not a `Success`. Alternatively, you could introduce a monadic chaining that is able to pipe `Result<T>` objects through many functions then handle at the end.
- aecorredor 7y agoCheck out the chapter on handling errors in the book “Programming TypeScript”, it gives a solid pattern for achieving something very close to Rust’s Option.
- meheleventyone 7y agoI did this super simple version of a Result and Optional types you can of course go further: https://gist.github.com/meheleventyone/b7b504052c589829885fe42f7db9ba14 https://gist.github.com/meheleventyone/b7b504052c589829885fe...
- TomMarius 7y agoI would like to recommend fp-ts over other JS/TS functional libraries, already contains types like Option