Skip to content

Add async error handling hook #1264

@bjnewman

Description

@bjnewman

🚀 Feature request

Current Behavior

We don't currently have any platform components to assist developers with error handling.

Desired Behavior

We should provide hooks and/or components that assist developers with error handling.

Suggested Solution

For example, in the common use case where devs need to handle errors during events and lifecycle hooks we should provide default hooks that surface async errors so they can be caught and handled by error boundaries rather than putting error handling logic in each component.

Something like
import { useCallback, useState } from 'react'

/* Hook to get a callback function for throwing
synchronous error from asynchronous code
When this callback is used somewhere within an error boundary,
it will trigger it, even if you are in an async block

const throwError = useGlobalError()
async function foo() { 
useEffect(async () => 
try {
 const resp = fetch('users') // throws on 403 response
 setResponse(resp)
} catch (e) {
throwError(e)
}
,[])

*/
export default function useGlobalError(): (e: Error) => void {
const [, setError] = useState()
return useCallback((e: Error) => {
setError(() => {
throw e
})
}, [])
}

Who does this impact? Who is this for?

All users

Describe alternatives you've considered

The react-error-boundary library exposes other utilities to help users handle errors, we could simply make a wrapper around that to let users know that it is a platform pattern they are expected to follow.

Additional context

Throwing inside of a setState was at one point Dan Abramov's recommended pattern for surfacing async errors. facebook/react#14981 (comment)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions