從 JSON.parse 捕獲異常的正確方法


捕獲無效 JSON 解析錯誤的最有效方法是將 JSON.parse() 呼叫放入 try/catch 塊中。

示例

function parseJSONSafely(str) {
   try {
      return JSON.parse(str);
   }
   catch (e) {
      console.err(e);
      // Return a default object, or null based on use case.
      return {}
   }
}

更新於: 02-Dec-2019

4K+ 瀏覽量

開啟你的職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.