在我的应用程序上,我try 实现一个简单的登录,如果我的服务器正在运行,该登录可以正常工作.但当我的后台离线时,我会try 捕捉错误并将其显示给用户.但即使我用try/catch包装了所有内容并处理这些错误,我仍然会在我的控制台中出现不必要的错误.在这种情况下,我不明白为什么我无法在apiLoginMutation中捕获错误,但在我的控制台中得到一个未捕获的错误.
My used setup
- 快速 ( 使用 TypeScript )
- react
- TanStack查询
- TanStack 路由
- Axios
- react Hook Form
这就是我安排一切的方式.
AuthPage Component
const AuthPage = () => {
const {
register,
handleSubmit,
formState: { errors },
} = useForm<LoginFormSchemaType>({
resolver: zodResolver(LoginFormSchema),
defaultValues: {
email: "",
password: "",
},
});
const { mutateAsync: apiLoginMutation } = useMutation({
mutationFn: APILogin,
onSuccess: () => {
//Handle the redirect
},
onError: (error: AxiosError) => {
console.log("Error in onError: " + error.message);
},
});
const onSubmit = async (data: LoginFormSchemaType) => {
try {
apiLoginMutation(data);
} catch (error) {
console.log("Error on apiLoginMutation call: " + error); //This never gets called!
}
};
return ( //JSX Stuff as Form)
};
http.ts
import axios from "axios";
const API_URL = "http://localhost:8000/api";
export type LoginData = {
email: string;
password: string;
};
export async function APILogin(formData: LoginData) {
try {
const { data } = await axios.post(
`${API_URL}/login`,
{ email: formData.email, password: formData.password },
{ withCredentials: true }
);
axios.defaults.headers.common["Authorization"] = `Bearer ${data.token}`;
} catch (err) {
throw err;
}
}
如上所述,我试图将所有内容打包在try/cakes中,但从未达到这一点,即没有向我的控制台显示任何错误.还try 构建我的应用程序(使用vite)并作为预览运行.所有错误仍然可见,因为我每次都读到了一些要显示的DEVMode部件,但它们甚至出现在生产版本中,所以我无法证实这些理论