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

在JavaScript中是否可以将try/catch改写为if/else?如何实现?

try/catch转if/else实现方案

结论

可以实现,不过因为JSON.parse解析非法格式字符串时会直接抛出异常,没有原生的API可以提前100%准确判断输入是否符合JSON规范,所以我们需要先把错误捕获逻辑封装为工具函数,再在外层用if/else做分支判断。

具体实现步骤

1. 封装安全JSON解析工具函数

提前把可能抛错的解析逻辑封装,返回统一格式的结果供外层判断:

// 安全JSON解析工具:解析成功返回{ data: 解析结果, error: null },失败返回{ data: null, error: 错误对象 }
function safeJsonParse(str) {
  let data = null;
  let error = null;
  try {
    data = JSON.parse(str);
  } catch (err) {
    error = err;
  }
  return { data, error };
}

2. 改写原getNotes方法

将原有的try/catch块替换为基于解析结果的if/else分支:

// Retrieves notes from storage
getNotes() {
  return this.read().then((notes) => {
    let parsedNotes;
    const parseResult = safeJsonParse(notes);
    // 用if/else判断解析状态走对应分支
    if (parseResult.error === null) {
      parsedNotes = [].concat(parseResult.data);
    } else {
      // 解析失败返回空数组
      parsedNotes = [];
    }
    return parsedNotes;
  });
}
// Adds note to array of notes
addNote(note) {
  const { 
    title, 
    text 
  } = note;
  const newNote = { 
    title, 
    text, 
    id: uuidv4() 
  };
  return this.getNotes()
    .then((notes) => [...notes, newNote])
    .then((updatedNotes) => this.write(updatedNotes))
    .then(() => newNote);
}

注意事项

  • 该方案本质是将try/catch收敛到了公共工具函数中,没有办法完全脱离try/catch实现该需求:如果强行自己实现JSON格式校验,需要逐字符匹配JSON语法规则,开发成本极高,运行性能也远低于原生实现
  • 日常开发中直接用try/catch包裹JSON.parse是行业通用的最佳实践,代码可读性和执行效率都更高,没有特殊需求不建议做这种改写

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 22:06:03