如何在Nuxt 3中使用useFetch获取错误响应体?
解决Nuxt 3中获取API错误响应消息的问题
问题原因
Nuxt 3的useFetch默认会在接收到非2xx状态码时,将data设为null,并把error设为FetchError对象,但这个错误对象不会自动包含API返回的响应体内容。要获取API返回的错误消息,需要手动从原始响应中解析。
方案一:修改服务层统一处理错误
修改/services/userService.js,配置throwOnError: false关闭自动抛出错误,手动处理所有状态码并返回结构化结果:
const baseURL = 'http://localhost:8080/api/auth/' const headers = { Accept: 'application/json', 'Content-type': 'application/json', } export default { async signinNewUser(firstName, secondName, email, password) { const { data, error, response } = await useFetch('/signup', { method: 'POST', baseURL: baseURL, headers: headers, body: { firstName, secondName, email, password, }, throwOnError: false // 禁用自动抛出错误,保留完整响应 }) // 处理错误状态码(4xx/5xx) if (response.value && response.value.status >= 400) { const errorData = await response.value.json() return { success: false, message: errorData.message } } // 处理网络类错误 if (error.value) { return { success: false, message: '网络请求失败,请稍后重试' } } // 请求成功 return { success: true, data: data.value } }, }
然后在/store/user.js中直接使用返回的结果:
async registerUser(firstName, secondName, email, password) { const result = await userService.signinNewUser(firstName, secondName, email, password) if (result.success) { this.registered = true } else { // 这里可以拿到API返回的具体错误消息,比如"Error: Email is already in use!" console.log(result.message) // 将错误消息存入store,方便页面组件展示给用户 this.errorMessage = result.message } },
方案二:在Store层直接解析响应
如果不想修改服务层代码,也可以在Store中通过response对象直接解析错误响应体:
async registerUser(firstName, secondName, email, password) { const { data, error, response } = await userService.signinNewUser(firstName, secondName, email, password) if (error.value) { if (response.value) { try { // 从原始响应中解析错误消息 const errorData = await response.value.json() console.log(errorData.message) this.errorMessage = errorData.message } catch (parseError) { console.log('解析错误消息失败', parseError) this.errorMessage = '请求出错,请稍后重试' } } else { // 处理无响应的网络错误 console.log(error.value) this.errorMessage = '网络连接异常,请检查网络' } } else { this.registered = true } },
关键说明
response.value包含了完整的HTTP响应对象,无论状态码是否正常,都可以通过它的json()方法读取响应体内容。- 配置
throwOnError: false可以让useFetch不自动抛出错误,避免进入Promise的catch分支,方便我们统一处理所有响应情况。
内容的提问来源于stack exchange,提问作者RazorMx
相关产品推荐
相关产品推荐

