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

Nuxt3中能否将useFetch返回的错误转换为自定义类实例?

在Nuxt3中使用自定义类实例处理useFetch错误

可以实现,但需要解决服务端到客户端的数据序列化问题——Nuxt会自动序列化useFetch的返回结果(包括错误),自定义类实例会被转为普通对象,导致原型方法丢失,这就是你遇到getErrorMessage is not a function错误的原因。

解决方案步骤

1. 定义带序列化/反序列化逻辑的自定义错误类

创建包含toJSON(序列化)和静态fromJSON(反序列化)方法的错误类,同时标记类型以便识别:

// ~/utils/ApiResponseError.js
export class ApiResponseError extends Error {
  constructor(response) {
    super(response._data?.message || '请求失败');
    this.name = 'ApiResponseError';
    this.status = response.status;
    this.data = response._data;
  }

  getErrorMessage() {
    return this.data?.message || this.message;
  }

  toJSON() {
    return {
      name: this.name,
      message: this.message,
      status: this.status,
      data: this.data,
      __type: 'ApiResponseError' // 用于识别自定义错误类型
    };
  }

  static fromJSON(json) {
    const error = new ApiResponseError({
      status: json.status,
      _data: json.data
    });
    error.message = json.message;
    error.name = json.name;
    return error;
  }
}

2. 配置Nuxt Payload插件处理反序列化

创建插件拦截payload提取过程,将序列化后的普通对象重建为自定义错误实例:

// ~/plugins/payload.ts
import { defineNuxtPlugin } from '#app';
import { ApiResponseError } from '~/utils/ApiResponseError';

export default defineNuxtPlugin(nuxtApp => {
  nuxtApp.hook('app:payload:beforeExtract', (payload) => {
    // 检查并重建自定义错误实例
    if (payload.data?.error?.__type === 'ApiResponseError') {
      payload.data.error = ApiResponseError.fromJSON(payload.data.error);
    }
  });
});

3. 在useFetch中使用自定义错误

修改拦截器抛出自定义错误,现在客户端就能正常调用实例方法:

// 组件中(如app.vue)
import { ApiResponseError } from '~/utils/ApiResponseError';

const transformError = ({ response }) => {
  throw new ApiResponseError(response);
};

const { data, error } = useFetch('/api/error', {
  onResponseError: transformError
});

// 调用自定义方法
if (error.value) {
  console.log(error.value.getErrorMessage());
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 22:15:23