如何在Fetch错误处理中正确填充Error对象的消息属性?
如何正确填充fetch错误对象的msg属性?
问题说明
需要将错误对象{'status': response.status, 'msg': ''}的msg属性填充为API JSON响应中携带的错误信息(若存在);若不存在或解析JSON失败,则抛出不带消息的错误对象。但当前代码中throw {'status': response.status, 'msg': ''}语句在response.json()的Promise解析前就执行,导致每次都得到空消息。
原代码
return await fetch(url.toString(), { method: 'post', headers: get_headers(url, request_body), body: JSON.stringify(request_body) }) .then((response) => { console.log(`API Status: ${response.status} API ${url.toString()}`) if (!response.ok) { // response.json() // .then(json_response => { // console.log(json_response) // logger.error(json_response) // throw {'status': response.status, 'msg': json_response?.errorMessage?.message} // }) // .catch((e)=>{ // throw e // }) throw {'status': response.status, 'msg': ''} } return response.json() }) .then((json_response) => { return json_response }) }
解决方案
方案一:使用async/await简化异步处理
将then回调改为异步函数,先完成JSON解析(或确认解析失败),再抛出错误对象:
return await fetch(url.toString(), { method: 'post', headers: get_headers(url, request_body), body: JSON.stringify(request_body) }) .then(async (response) => { console.log(`API Status: ${response.status} API ${url.toString()}`) if (!response.ok) { let errorMsg = ''; try { // 尝试解析响应的JSON const json_response = await response.json(); // 提取错误信息,不存在则保持空字符串 errorMsg = json_response?.errorMessage?.message || ''; } catch (e) { // 解析JSON失败(比如响应不是JSON格式),保持errorMsg为空 } // 抛出携带正确msg的错误对象 throw { status: response.status, msg: errorMsg }; } return response.json(); })
方案二:使用Promise链式调用
通过链式then处理JSON解析逻辑,确保错误在解析完成后抛出:
return await fetch(url.toString(), { method: 'post', headers: get_headers(url, request_body), body: JSON.stringify(request_body) }) .then((response) => { console.log(`API Status: ${response.status} API ${url.toString()}`) if (!response.ok) { // 先解析JSON,成功则提取错误信息抛出,失败则抛出空msg错误 return response.json() .then(json_response => { throw { status: response.status, msg: json_response?.errorMessage?.message || '' }; }) .catch(() => { throw { status: response.status, msg: '' }; }); } return response.json(); })
关键说明
- 原注释代码的问题:
response.json().then()内部throw的错误无法被外层Promise链正确捕获,因为外层代码会直接执行后续逻辑,等待JSON解析的异步操作还未完成。 - 两种方案都确保了先完成JSON解析(或确认解析失败),再抛出携带正确
msg的错误对象,解决了异步顺序问题。
内容的提问来源于stack exchange,提问作者kajezevu
相关产品推荐
相关产品推荐

