在我的应用程序上,我try 实现一个简单的登录,如果我的服务器正在运行,该登录可以正常工作.但当我的后台离线时,我会try 捕捉错误并将其显示给用户.但即使我用try/catch包装了所有内容并处理这些错误,我仍然会在我的控制台中出现不必要的错误.在这种情况下,我不明白为什么我无法在apiLoginMutation中捕获错误,但在我的控制台中得到一个未捕获的错误.

My used setup

  • 快速 ( 使用 TypeScript )
  • react
  • TanStack查询
  • TanStack 路由
  • Axios
  • react Hook Form

My console output

这就是我安排一切的方式.

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部件,但它们甚至出现在生产版本中,所以我无法证实这些理论

推荐答案

        try {
            apiLoginMutation(data);
        } catch (error) {
            console.log("Error on apiLoginMutation call: " + error); //This never gets called! 
        }

此部分不会捕获任何错误,因为apiLoginMutation是c,您需要await它.

        try {
            await apiLoginMutation(data);
        } catch (error) {
            console.log("Error on apiLoginMutation call: " + error); //This never gets called! 
        }

这应该会带来改变.

Typescript相关问答推荐

如何在不使用变量的情况下静态判断运算式的类型?

动态判断TypScript对象是否具有不带自定义类型保护的键

在TypeScript中,除了映射类型之外还使用的`in`二进制运算符?

泛型和数组:为什么我最终使用了`泛型T []`而不是`泛型T []`?<><>

在泛型类型中对子代执行递归时出错

在MessageStore对象中实现条件类型时出现TypeScrip错误

如何在编译时为不带常量的参数引发错误

通过按键数组拾取对象的关键点

如何在NX工作区项目.json中设置类似angular.json的两个项目构建配置?

在排版修饰器中推断方法响应类型

避免混淆两种不同的ID类型

错误TS7030:并非所有代码路径都返回值.";由tsfig.json中的";Strong";:False引起

KeyOf关键字在特定示例中是如何工作的

使用Cypress测试从Reaction受控列表中删除项目

使用RXJS获取数据的3种不同REST API

React Context TypeScript错误:属性';firstName';在类型';iCards|iSearch';

如何创建允许使用带有联合类型参数的Array.from()的TS函数?

断言同级为true或抛出错误的Typescript函数

使用受保护的路由和入门来响应路由

是否可以从 TypeScript 的类型推断中排除this?