feat: 使用 safeClient 封装 API 调用并处理错误提示

This commit is contained in:
2025-12-14 20:40:17 +07:00
parent 9d6bceb6cd
commit f112371efa
2 changed files with 26 additions and 13 deletions

View File

@@ -1,5 +1,6 @@
import type { App } from "@riwa/api-types"; import type { App } from "@riwa/api-types";
import { treaty } from "@elysiajs/eden"; import { treaty } from "@elysiajs/eden";
import { toastController } from "@ionic/vue";
const client = treaty<App>(window.location.origin, { const client = treaty<App>(window.location.origin, {
fetch: { fetch: {
@@ -7,4 +8,27 @@ const client = treaty<App>(window.location.origin, {
}, },
}); });
export async function safeClient<T, E>(
requestPromise: Promise<{ data: T; error: E | null }>,
options: { silent?: boolean } = {},
) {
const { data, error } = await requestPromise;
if (error) {
if (!options.silent) {
const toast = await toastController.create({
message: typeof error === "string" ? error : "Request failed. Please try again.",
duration: 3000,
position: "bottom",
color: "danger",
});
await toast.present();
}
throw error;
}
return { data, error };
}
export { client }; export { client };

View File

@@ -1,7 +1,7 @@
<script lang='ts' setup> <script lang='ts' setup>
import type { WithdrawBody } from "@/api/types"; import type { WithdrawBody } from "@/api/types";
import { toastController } from "@ionic/vue"; import { toastController } from "@ionic/vue";
import { client } from "@/api"; import { client, safeClient } from "@/api";
import { AssetCodeEnum, ChainEnum, WithdrawMethodEnum } from "@/api/enum"; import { AssetCodeEnum, ChainEnum, WithdrawMethodEnum } from "@/api/enum";
const amountInputInst = useTemplateRef<InputInstance>("amountInputInst"); const amountInputInst = useTemplateRef<InputInstance>("amountInputInst");
@@ -40,18 +40,7 @@ function handleCurrentChange() {
} }
async function onSubmit() { async function onSubmit() {
const { data, status } = await client.api.asset.withdraw.post(form.value); const { data } = await safeClient(client.api.asset.withdraw.post(form.value));
if (status === 200) {
const toast = await toastController.create({
message: "Submission successful!",
duration: 1500,
position: "bottom",
});
await toast.present();
resetForm();
}
} }
</script> </script>