gracekrcx / weekly-notes

4 stars 0 forks source link

(筆記)Unexpected end of JSON input Error in JavaScript #144

Open gracekrcx opened 1 year ago

gracekrcx commented 1 year ago

The JavaScript exceptions thrown by JSON.parse() occur when string failed to be parsed as JSON.

SyntaxError: JSON.parse: unterminated string literal
SyntaxError: JSON.parse: bad control character in string literal
SyntaxError: JSON.parse: bad character in string literal
SyntaxError: JSON.parse: bad Unicode escape
...
...

Proper way to catch exception from JSON.parse Unexpected end of JSON input Error in JavaScript SyntaxError: JSON.parse: bad parsing

try {
    var a = JSON.parse("{'foo': 1}");
    console.log('success:', a); 
  } catch (error) {
    console.log('error:錯誤', error.message);
  }

try {
    var a = JSON.parse("[]");
    console.log('success:', a); 
  } catch (error) {
    console.log('error:錯誤', error.message);
  }

try {
    var a = JSON.parse("");
    console.log('success:', a); 
  } catch (error) {
    console.log('error:錯誤', error.message);
  }
gracekrcx commented 1 year ago
const getLocalStorage = name => {
    try {
        return JSON.parse(localStorage.getItem(name))
    } catch (e) {
        console.error(e)
        return false
    }
}
const res = getLocalStorage('products')

// console.log(!!res, res, typeof res)
// console.log(Array.isArray(res))
const products = Array.isArray(res) ? res : []
gracekrcx commented 1 year ago

Control flow and error handling

function f() {
  try {
    throw "bogus";
  } catch (e) {
    console.log('caught inner "bogus"');
    // This throw statement is suspended until
    // finally block has completed
    throw e;
  } finally {
    return false; // overwrites the previous "throw"
  }
  // "return false" is executed now
}

try {
  console.log(f());
} catch (e) {
  // this is never reached!
  // while f() executes, the `finally` block returns false,
  // which overwrites the `throw` inside the above `catch`
  console.log('caught outer "bogus"');
}

// Logs:
// caught inner "bogus"
// false
gracekrcx commented 1 year ago

例外狀況處理語句 - throw 、 try-catch 、 try-finally 、 和 try-catch-finally 敏捷式例外處理設計 (4):我到底哪裡做錯之 nested try block Is using nested try-catch blocks an anti-pattern? 去除 try/catch,實作簡潔的 Async 和 Await!