Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
gracekrcx opened this issue Aug 23, 2023 · 3 comments
Open

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

gracekrcx opened this issue Aug 23, 2023 · 3 comments

Comments

@gracekrcx
Copy link
Owner

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
Copy link
Owner Author

gracekrcx commented Aug 24, 2023

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
Copy link
Owner Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant