Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add async error handling hook #1264

Open
bjnewman opened this issue Apr 4, 2023 · 0 comments
Open

Add async error handling hook #1264

bjnewman opened this issue Apr 4, 2023 · 0 comments

Comments

@bjnewman
Copy link
Contributor

bjnewman commented Apr 4, 2023

🚀 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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant