baconjs / bacon.js

Functional reactive programming library for TypeScript and JavaScript
https://baconjs.github.io
MIT License
6.47k stars 331 forks source link

Errors not captured in methods? #809

Closed jaidetree closed 3 weeks ago

jaidetree commented 3 weeks ago

Given code like the following:

Bacon
 .once(null)
 .map((_x) => {
   throw new Error("Expected failure")
 }) 
 .toPromise()
 .then(x => {
  console.log("Promise was unexpectedly resolved")
 })
 .catch(x => {
   if (x instanceof Error && x.message.includes("Expected failure")) {
     console.log("Handled the expected failure")
   } else {
     console.log("Something went wrong")
   }
 })

I expect the error in the map operator to make its way through the promise, then the catch handler can test the error and log my expected message.

Instead, the stream exits immediately and it seems like an error is thrown outside of the stream.

Is the idea that I should be wrapping my logic in a try...catch clause or is this an unexpected bug?

raimohanska commented 3 weeks ago

It’s intended - Bacon has never caught exceptions. The thinking is that exceptions are treated as programming errors and should fail fast. Which is ofc opinionated.

jaidetree commented 3 weeks ago

Thanks for the insight, seems reasonable

semmel commented 2 weeks ago

@jaidetree Otherwise you can use Bacon.try together with .flatMap like this:

wrapped = source.flatMap(Bacon.try(dangerousOperation))

jaidetree commented 2 weeks ago

That's perfect thanks!