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

js catch binding #62

Open
chenxiaochun opened this issue Aug 30, 2018 · 0 comments
Open

js catch binding #62

chenxiaochun opened this issue Aug 30, 2018 · 0 comments

Comments

@chenxiaochun
Copy link
Owner

chenxiaochun commented Aug 30, 2018

Optional catch binding 提议目前处于 Stage 3,这篇文章就是来解释一下它是如何工作的。

概述

我们平时使用try catch时,一般都是如下姿势:

try {
    ···
} catch (error) {
    ···
}

可是当我们不需要error参数时,也并不能将其省略。因为 js 并不允许以下的语法:

try {
    ···
} catch() {
    ···
}

那么,此提议的意义就是当你不需要error参数时,可以将其省略:

try {
    ···
} catch {
    ···
}

使用场景

场景1:JSON.parse()

使用JSON.parse()时,如果传给它的是一个非预期类型值,一般它就会抛异常:

> JSON.parse('abc')
SyntaxError: Unexpected token a in JSON at position 0

针对此情况,你可以这样处理:

let jsonData;
try {
    jsonData = JSON.parse(str); // (A)
} catch {
    jsonData = DEFAULT_DATA;
}

但是,这种使用方式会引起另外一个问题。当 A 行代码报错时,它会被静默忽略,即使你可能只是一个拼写错误。这个问题也曾经困扰过我很长时间。因此,我更倾向于使用以下带有条件的抛出异常:

let jsonData;
try {
    jsonData = JSON.parse(str);
} catch (err) {
    if (err instanceof SyntaxError) {
        jsonData = DEFAULT_DATA;
    } else {
        throw err;
    }    
}

场景2:属性链

原文链接

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