You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pinia中为Google Apps API的google.script.run配置withFailureHandler?

在Pinia Store中使用google.script.run的错误处理

你只需要在google.script.run的链式调用中添加withFailureHandler,指定对应的错误处理回调函数即可,和withSuccessHandler的用法完全一致。

修改后的完整Store代码

import { defineStore } from 'pinia'
export const useMainStore = defineStore('mainStore',
    {
        state: () => {
            return {
                persons: [{}],
                fetchError: null // 新增错误状态字段,用于存储错误信息
            }
        },
        actions: {
            fetchPersons() {
                // 发起请求前重置错误状态
                this.fetchError = null
                console.log('fetching persons in store')
                // 链式调用设置成功、失败回调,最后执行目标函数
                google.script.run
                    .withSuccessHandler(this.fetchPersonsSuccess)
                    .withFailureHandler(this.fetchPersonsFailure)
                    .fetchPersons()
            },
            fetchPersonsSuccess(data) {
                console.log('receiving data in store')
                console.log(data)
                this.persons = data
            },
            fetchPersonsFailure(error) {
                console.error('获取人员列表失败:', error)
                // 将错误信息存入state,方便组件中获取并展示
                this.fetchError = error
                // 这里还可以扩展其他逻辑:比如全局提示、错误上报等
            },
        }
    }
)

关键说明

  • withFailureHandler接收的参数就是Google Apps Script端抛出的错误(可能是Error对象或字符串),你可以在回调里做任意错误处理。
  • 建议在state中添加错误状态字段,这样组件能直接获取错误信息并展示给用户。
  • withSuccessHandler和withFailureHandler的调用顺序不影响,只要在执行目标函数(fetchPersons())之前设置即可。

组件中使用错误状态示例(Vue3)

<template>
  <div>
    <button @click="store.fetchPersons">获取人员列表</button>
    <!-- 展示错误信息 -->
    <div v-if="store.fetchError" class="error-tip">
      操作失败:{{ store.fetchError.message || store.fetchError }}
    </div>
    <!-- 渲染人员列表 -->
    <ul>
      <li v-for="person in store.persons" :key="person.id">{{ person.name }}</li>
    </ul>
  </div>
</template>

<script setup>
import { useMainStore } from './stores/mainStore'
const store = useMainStore()
</script>

<style scoped>
.error-tip {
  color: #ff4d4f;
  margin: 12px 0;
}
</style>

内容的提问来源于stack exchange,提问作者Meaulnes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 01:45:22