首页 > 移动开发 > 移动测试 > 快应用如何避免JSON.parse()解析出错
代码执行 fetch 请求,请求返回的数据默认是 JSON 化的字符串了,开发者使用 JSON 对象解析,这是正常逻辑;
但是一旦遇到服务器端权限校验失败等问题时,会返回类似 503 的 HTML 页面,此时 JSON 解析肯定就会失败。
1. 在每个JSON.parse() 的代码执行处进行 try-catch 包围,处理出错情况
2. 在 app.ux 中提前代理 JSON.parse() ,使用 try-catch 包围,待异常出现时埋点数据,或者返回默认正常数据替代。
推荐方案2 ,示例代码如下:
export function parseProxy () {
const rawParse = JSON.parse
JSON.parse = function (str, defaults) {
try {
return rawParse(str)
}
catch (err) {
console.error(`JSON解析失败:${str}, ${err.stack}`)
return defaults
}
}
}
原文链接: https://developer.huawei.com/consumer/cn/forum/topic/0201454971771540781?fid=0101271690375130218
原作者: Mayism
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69970551/viewspace-2782023/ ,如需转载,请注明出处,否则将追究法律责任。