Skip to content

Commit

Permalink
feat(useObservable): now supports optional error handling via `onErro…
Browse files Browse the repository at this point in the history
…r`. (vitest-dev#567)

Adds a few feature to allow users to configure error handling if they so choose. Without this feature, any error from the source observable would be treated as "unhandled" by RxJS, and thrown in a new call stack.

Resolves vitest-dev#566
  • Loading branch information
benlesh committed Jun 9, 2021
1 parent a1aff91 commit 807a890
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
31 changes: 30 additions & 1 deletion packages/rxjs/useObservable/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,42 @@ const count = useObservable(
)
```

If you want to add custom error handling to an observable that might error, you can supply an optional `onError` configuration. Without this, RxJS will treat any error in the supplied observable as an "unhandled error" and it will be thrown in a new call stack and reported to `window.onerror` (or `process.on('error')` if you happen to be in node).

```ts
import { ref } from 'vue'
import { useObservable } from '@vueuse/rxjs'
import { interval } from 'rxjs'
import { map } from 'rxjs/operators'

// setup()
const count = useObservable(
interval(1000).pipe(
map(n => {
if (n === 10) {
throw new Error('oops')
}
return n + n
})
),
{
onError: err => {
console.log(err.message) // "oops"
}
}
)
```

<!--FOOTER_STARTS-->
## Type Declarations

```typescript
export interface UseObservableOptions {
onError?: (err: any) => void
}
export declare function useObservable<H>(
observable: Observable<H>
observable: Observable<H>,
options?: UseObservableOptions
): Readonly<Ref<H>>
```

Expand Down
11 changes: 9 additions & 2 deletions packages/rxjs/useObservable/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,16 @@ import { Observable } from 'rxjs'
import { Ref, ref } from 'vue-demi'
import { tryOnUnmounted } from '@vueuse/shared'

export function useObservable<H>(observable: Observable<H>): Readonly<Ref<H>> {
export interface UseObservableOptions {
onError?: (err: any) => void
}

export function useObservable<H>(observable: Observable<H>, options?: UseObservableOptions): Readonly<Ref<H>> {
const value = ref<H | undefined>()
const subscription = observable.subscribe(val => (value.value = val))
const subscription = observable.subscribe({
next: val => (value.value = val),
error: options?.onError,
})
tryOnUnmounted(() => {
subscription.unsubscribe()
})
Expand Down

0 comments on commit 807a890

Please sign in to comment.