如何用Redux验证登录邮箱与密码?错误输入致API崩溃
问题解决方法
前端代码修复
你的核心问题是异步错误未被正确捕获:login 是异步函数,但你在 handleClick 里调用时没有用 await,导致外层的 try/catch 无法捕获异步错误;同时 login 内部的 catch 只做了 dispatch,没有把错误抛出给上层处理。
修改步骤:
- 把
handleClick改为异步函数,调用login时添加await:
const handleClick = async (e) => { e.preventDefault() try { await login(dispatch, { email, password }) // 登录成功后再执行跳转 history.push("/") } catch (error) { Swal.fire({ position: 'top-end', icon: 'error', title: 'Email atau Password tidak sesuai', showConfirmButton: false, timer: 1500, }) } }
- 在
login函数的catch块中抛出错误,让上层的try/catch能捕获到:
export const login = async (dispatch, user) => { dispatch(loginStart()) try { const res = await axios.post(BASE_URL + 'auth/login', user) dispatch(loginSuccess(res.data)) } catch (error) { dispatch(loginFailure(error)) // 抛出错误给上层处理 throw error } }
API端检查
如果输入错误凭证时API真的崩溃(返回500状态码),需要后端修复API逻辑:
- 验证用户输入时,对于错误的邮箱/密码,应该返回401 Unauthorized或400 Bad Request的合法响应,而不是让服务器崩溃。
内容的提问来源于stack exchange,提问作者Reihan Wiyanda
相关产品推荐
相关产品推荐

