Proposal: GitHub - rafageist/proposal-universal-catch-and-when: Expands JavaScript's error-handling by allowing any block to have catch and finally blocks with optional when clauses for conditional error handling.
This proposal expands JavaScript's current try-catch
mechanism by allowing any code block to have an optional catch
and finally
block. The catch
block can also be enhanced with a when
clause, enabling conditional error handling directly within the block. This approach maintains consistency with JavaScript's existing syntax and structure, offering a natural extension of control flow mechanisms without introducing new, complex constructs.
/*
any block of code: try, anonymous, functions,
if, do, class, catch, finally, switch, ...
*/
{
// Code that may throw an error
// ...
}
catch (<var>) when (<boolean expression)
{
// Error-handling logic
// ...
// catch is also a block!
}
catch (<var>) when (<boolean expression>)
{
// Error-handling logic
// ...
}
finally
{
// Cleanup code, executed regardless of success or failure
// ... but finally is also a block!
}
catch (<var>) when (<boolean expression>)
{
// Error-handling logic
// ...
}
...
Examples
Anonymous block
{
doSomething();
}
catch(err) when (err instanceof Error)
{
console.log("Error: ", err);
}
catch(err) when (err instanceof TypeError)
{
console.log("TypeError: ", err);
}
finally
{
console.log("Finally block");
}
Function block
async function loadData()
{
return await fetch("https://api.example.com");
}
catch (err)
{
console.log("Error fetch data");
}
If and else block
if (condition == false)
{
console.log("Condition is false");
}
catch(err) when (err instanceof Error)
{
console.log("Error condition");
}
else
{
console.log("Condition is true");
}
catch(err) when (err instanceof TypeError)
{
console.log("Error in else block");
}
finally
{
console.log("Finally block after if-else");
}
For loop block
for (let i = 0; i < 10; i++)
{
console.log(i);
}
catch (err)
{
console.log("Error in loop");
}
Switch block
switch (condition)
{
case 1:
console.log("Case 1");
break;
case 2:
console.log("Case 2");
break;
default:
console.log("Default case");
}
catch (err)
{
console.log("Error in switch");
}
Class block
class MyClass
{
constructor()
{
console.log("MyClass constructor");
}
}
catch (err)
{
console.log("Error in class");
}
... and more!
This proposal is currently in need of a champion to help refine and present it to the TC39 committee. If you're interested in advocating for more flexible and structured error handling in JavaScript, your support would be invaluable. For more details, please read the proposal in the repository.