简体   繁体   中英

Component can't catch error from function passed as a prop

I have a Form component, and when the submit button is clicked, it calls:

//Form.js
    //...
    const submit = () => {
            try {
                onSubmit(values); //onSubmit from props, values from state
            } catch (error) {
                console.log(error);
                setSubmitError(error);
            }
    }
    //...

I'm trying to use it with onSubmit passed as:

export const signIn = ({ email, password }) => (
    auth()
    .signInWithEmailAndPassword(email, password)
    .catch(e => { throw e })
);

But it doesn't handle it. In the current version, it throws an error to the console: auth.esm.js:429 Uncaught The email address is badly formatted. I tried wrapping the error with new Error , but then it throws it to the window. What am I doing wrong?

A normal try/catch block cannot catch async errors. However you can declare an async block and this should work:

const submit = async () => {
            try {
                await onSubmit(values); //onSubmit from props, values from state
            } catch (error) {
                console.log(error);
                setSubmitError(error);
            }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM