捕获未运行javascript的错误
我有一个异步等待函数,用于在React Native中处理表单提交:捕获未运行javascript的错误,javascript,reactjs,react-native,asynchronous,Javascript,Reactjs,React Native,Asynchronous,我有一个异步等待函数,用于在React Native中处理表单提交: const handleSubmit = async () => { const credentials = { email, password } try { login(credentials) } catch { console.error('ERROR') //external function to reset form resetForm
const handleSubmit = async () => {
const credentials = { email, password }
try {
login(credentials)
} catch {
console.error('ERROR')
//external function to reset form
resetForm()
return
}
// User authenticated, go to home screen
await goToHomeScreen()
}
其中,进行API调用的login()是
const login = (credentials) => {
axios
.post(`${MY_API}/login`, credentials)
.then((res) => {
console.log(res.data)
})
.catch(() => {
throw 'Error'
})
}
其思想是,如果身份验证调用失败,my login()将抛出一个错误,该错误将在我的handleSubmit的catch{}中运行
返回
,从而结束函数。但是,catch永远不会运行,而goToHomeScreen()会运行。我做错了什么?不仅仅是返回,而是做点什么
axios
.get(url)
.then((response) => {
console.log('response', response);
}
.catch((error) => {
console.log('CATCH');
window.alert('CATCH');
}
不只是回来,而是做点什么
axios
.get(url)
.then((response) => {
console.log('response', response);
}
.catch((error) => {
console.log('CATCH');
window.alert('CATCH');
}
试试这个,它对我有用
const login = (credentials) => {
axios
.post(`${MY_API}/login`, credentials)
.then((res) => {
console.log(res.data)
})
.catch((error ) => {
return Promise.reject(error);
})
}
试试这个,它对我有用
const login = (credentials) => {
axios
.post(`${MY_API}/login`, credentials)
.then((res) => {
console.log(res.data)
})
.catch((error ) => {
return Promise.reject(error);
})
}
由于您使用的是async await,因此可以调用login as:
const handleSubmit = async () => {
const credentials = { email, password }
try {
await login(credentials)
} catch {
console.error('ERROR')
//external function to reset form
resetForm()
return
}
// User authenticated, go to home screen
await goToHomeScreen()
}
const login = async (credentials) => {
return await axios.post(`${MY_API}/login`, credentials);
}
它将解决这个问题因为您使用的是async Wait,您可以通过以下方式调用login:
const handleSubmit = async () => {
const credentials = { email, password }
try {
await login(credentials)
} catch {
console.error('ERROR')
//external function to reset form
resetForm()
return
}
// User authenticated, go to home screen
await goToHomeScreen()
}
const login = async (credentials) => {
return await axios.post(`${MY_API}/login`, credentials);
}
它将解决这个问题。try
return axios.post…
这将使您能够抛出错误将return axios添加到login()似乎没有改变任何东西tryreturn axios.post…
这将使您能够抛出错误将return axios添加到login()似乎没有改变任何东西我还有其他动作要做,添加用于澄清更新我的答案,我的捕获在这里正确工作,URL无效错误为400网络不可用对我来说很好,检查这里我的捕获中有其他操作,添加用于澄清更新我的答案,我的CATCH在这里工作正常,URL无效错误为400网络不可用对我来说很好,检查这里。CATCH(error=>Promise.reject(error))
是多余的;结果与根本没有捕获是一样的。.catch(error=>Promise.reject(error))
是多余的;其结果与根本没有捕获相同。