Door 17 | JS Adventskalender
Skip to content

Door 17

Published: at 07:00 AMSuggest Changes

Optional Catch Binding – Simpler Error Handling

With the ES2019 update, JavaScript introduced a small but extremely practical improvement in error handling: Optional Catch Binding. This may seem like an insignificant syntactic detail at first glance, but in practice, it brings significantly simpler and clearer error handling.

What is Optional Catch Binding?

Before ES2019, every try...catch block in JavaScript had to specify a parameter in the catch block, even if the actual error was not needed. This led to code like this:

try {
  riskyOperation();
} catch (error) {
  console.log("An error occurred.");
  // But here we don't use 'error' at all.
}

The error object was mandatory, even if you completely ignored it. This can look confusing and lead to warnings from linting tools that complain about unused variables.

With Optional Catch Binding, it is now allowed to use the catch block without a parameter:

try {
  riskyOperation();
} catch {
  console.log("An error occurred, but details don't matter here.");
}

The error variable no longer needs to be explicitly specified if it’s not needed. This makes the code slimmer and much more expressive: it clearly shows that the specific error is not further processed, but only that something went wrong is being reacted to.

Why is This Useful?

There are situations where you only need to know that an error happened, not which one. This can be the case, for example, when:

Practical Examples

1. Simple Fallback:

let config;
try {
  config = JSON.parse(userInput);
} catch {
  // If parsing fails, use default configuration
  config = getDefaultConfig();
}

2. Feature Detection:

let supported = false;
try {
  newFeature();
  supported = true;
} catch {
  // Feature not supported, use fallback
  fallbackFeature();
}

3. Cleanup Operations:

function processData(data) {
  let tempFile = createTempFile();
  try {
    expensiveOperation(data, tempFile);
  } catch {
    // We don't care about the specific error,
    // just clean up
  } finally {
    deleteTempFile(tempFile);
  }
}

4. Silent Failure:

// Try to store in localStorage, but don't fail if it doesn't work
try {
  localStorage.setItem('key', value);
} catch {
  // Private browsing or quota exceeded - continue anyway
}

When to Use the Error Parameter

Of course, there are many cases where you do need the error object:

try {
  await fetchUserData();
} catch (error) {
  // Here we need the error details
  console.error('Failed to fetch user data:', error.message);
  logErrorToServer(error);
}

Conclusion

Optional Catch Binding is a small but fine improvement that makes JavaScript code cleaner and more expressive. It allows you to differentiate between cases where you need the error details and cases where you just want to react to the fact that an error occurred. This leads to more readable and maintainable code.

Use Optional Catch Binding in your next project and enjoy cleaner error handling!


Previous Post
Door 18
Next Post
Door 16