For AI agents: the complete documentation index is available at /tc39-atlas/llms.txt, the full documentation bundle is available at /tc39-atlas/llms-full.txt, and this page is available as Markdown at /tc39-atlas/proposals/year/pending/proposal-catch-guards.md.
  • 简体中文
  • Catch Guard S0

    中文标题:捕获守卫

    提案概览
    提案速览

    Catch Guard 提案通过添加捕获守卫来解决 JavaScript 中缺乏符合人体工程学的错误类型处理的问题,使开发者能够仅当异常匹配特定类时才捕获它们。它提出了两种语法选项:一种带有 BindingGuard 类型的新捕获语句,或一种与模式匹配结合的新 CatchPatten 语句。

    Note

    以下 README 来自上游仓库,其中的阶段或状态标注可能滞后;当前信息以提案概览为准。

    ECMAScript 捕获守卫

    本提案为语言添加了捕获守卫,使开发者能够仅当异常匹配特定类或类集合时才捕获它们。

    本提案大量借鉴了以下语言中已有的类似功能:JavaC#RubyPython

    问题陈述

    JavaScript 没有提供一种符合人体工程学的方式来处理不同类型的错误。

    状态

    提案倡导者: Willian Martins (Netflix, @wmsbill),

    阶段:0

    最近更新:草稿已创建

    动机

    • 开发者人体工程学

      如今,开发者必须捕获所有错误,添加 ifswitch 语句,即使他们只想捕获一种特定类型的错误,也需要重新抛出:

      class ConflictError extends Error {}
      
      try {
        something();
      } catch (err) {
        if (err instanceOf ConflictError) {
          // 处理它...
        }
        throw err;
      }
    • 与其他语言的一致性

      将错误处理限定到特定类型是几种编程语言中常见的构造,如:JavaC#RubyPython

    • 代码/引擎优化

    如果错误不匹配正确的类型,引擎可以完全跳过该块。

    语法选项

    当前实现使用以下语法:

     catch ( CatchParameter[?Yield, ?Await] ) { block }

    其中 CatchParameter 是:

    • BindingIdentifier[?Yield, ?Await]
    • BindingPattern

    选项 1 (新的捕获语句):

    本提案为 CatchParameter 引入了一种新的绑定类型,称为 BindingGuard;这种新绑定类型的形态和语义将在阶段 1 开发中确定。

      
    try {
      something();
    } catch (BindingGuard) {
      // 以某种方式处理...
    } catch(BindingGuard) {
      // 以另一种方式处理...
    } catch (err) {
      // 捕获所有...
    }

    选项 2 (新的捕获模式语句):

    此选项可以与选项一结合使用,或者利用模式匹配提案来绑定不同的错误模式(语法和语义将在阶段 1 开发中确定),从而保持 catch 语句的现有语法。

      
    try {
      something();
    } CatchPatten (BindingGuard) {
      // 以某种方式处理...
    } CatchPatten (BindingGuard) {
      // 以另一种方式处理...
    } catch (err) {
      // 捕获所有...
    }

    实现

    • Babel 插件 //待定