Optional catch Binding Drops Error Params

When the error object itself is not needed, ES2019 allows catch without a binding: parse failures fall through without declaring an unused parameter.

JavascriptResilience

Code

javascriptsnippet
21 lines
// 确定不需要错误对象时,ES2019 允许 catch 省略参数绑定
function readSettings(raw) {
  try {
    return { ok: true, value: JSON.parse(raw) };
  } catch {
    return { ok: false, value: null };
  }
}

const good = readSettings('{"retries": 2, "verbose": true}');
const bad = readSettings('{retries: 2'); // 语法错误 → 进入无绑定的 catch

console.log('good:', good.ok, JSON.stringify(good.value));
console.log('bad:', bad.ok, bad.value);

// catch 里拿不到 error 对象:确需区分原因时仍要写完整绑定
try {
  JSON.parse('[1, 2');
} catch {
  console.log('malformed JSON, reason not inspected');
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

good: true {"retries":2,"verbose":true}
bad: false null
malformed JSON, reason not inspected

What the code does

Optional catch Binding Drops Error Params is built around the function readSettings.

The result comes back as an object carrying true.

Applying it

The primary signature is function readSettings(raw)

The demo output is labeled (good:, bad:, malformed JSON, reason not inspected), so every printed line maps back to its originating operation.

The call returns true.

Statements that matter

return { ok: true, value: JSON.parse(raw) };
return { ok: false, value: null };

Interactive Tools for This Topic

FAQ

Does `readSettings` modify its input?
It does not. Inputs are only read; the return value is freshly built.
Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared. The file defines `readSettings` at load time.