Summary by TwinMind · 33m 7s

Summary by TwinMind · 33m 7s

This might fix error handling in JS

This might fix error handling in JS

Theo - t3․gg

Theo - t3․gg

JavaScript/TypeScript Error Handling Problems

  • Try-catch mechanism in JavaScript/TypeScript is suboptimal
  • Most TypeScript fans admit try-catch is far from ideal
  • Error handling method is rough, requiring libraries like Effect TS for runtime management
  • JavaScript lacks ability to safely call error-prone functions and get errors as values
  • Go's error-as-value approach is better - errors return as values to check before proceeding
  • JavaScript's try-catch prevents variable binding as expected, creates messy code

TC39 Safe Assignment Operator Proposal

  • Proposal by Arthur (community member working on K framework)
  • Official TC39 proposal for safe assignment operator using ?= syntax
  • Goal: use ?= with async/await to return tuple with error and actual response
  • Went viral - Kent's tweet got 1.5k likes
  • Matt Pocock noted it's stage 0 proposal (not guaranteed to ship)
  • Stage 0 means not acknowledged by standards committee
  • Likelihood of shipping is effectively zero

Building Safe Await Function

  • Demonstrated creating custom safeAwait function
  • Takes promise returning T, uses try-catch internally
  • Returns [null, result] on success, [error, null] on failure
  • Example async function mightFail() throws error 50% of time (random > 0.5)
  • Initial implementation lacks proper TypeScript types
  • Enhanced version with proper generic types and error handling
  • Final implementation provides full Go-like experience with proper type safety

Never Throw Library

  • Matt showcased Never Throw library as existing solution
  • Uses generator functions for error handling
  • safeTry helper provides result type similar to custom implementation
  • Smart enough to parse generator functions that never throw
  • Returns Result<string, Error> type for functions that might error
  • Allows writing code thinking about happy path while tracking all possible errors
  • Uses yield instead of return for error cases
  • Can hoist error types up through call stack using TypeScript types

Why Safe Assignment Operator Cannot Ship

  • David Blasé (TypeScript expert) identified fatal flaw
  • ?= syntax conflicts with existing nullish coalescing assignment (??=)
  • ??= assigns value only if variable is null/undefined
  • Example: x ??= "default" only assigns if x is null/undefined
  • Removing one question mark creates massive confusion
  • Breaks intuition about question mark relating to null/undefined
  • Syntax collision makes proposal unviable

TypeScript Throws Clause Proposal

  • Separate proposal for throws keyword to specify error types functions can throw
  • Would allow functions to declare specific error types they throw
  • Example: function fn() throws string
  • Enables better type inference for catch clause variables
  • Anders Hellsberg (C#/TypeScript creator) disagrees with checked exceptions
  • Article "The Trouble with Checked Expressions" explains difficulties

TypeScript Team's Position on Error Types

  • Ryan Cavanaugh (TypeScript team) provided detailed explanation
  • JavaScript runtime/ecosystem doesn't provide platform for this feature
  • Two main facets: typed exceptions and checked exceptions
  • JavaScript exception usage examination shows few guarantees on error types
  • Dynamic type testing pattern already appropriate for safe code

JavaScript Library Error Documentation Analysis

  • Lodash: 200 pages of docs, no exception descriptions
  • jQuery: One throwable error not mentioned in docs
  • React: Mentions some exceptions but not all, uses vague language
  • Material UI: 850-page book never mentions exceptions
  • XState: 100 pages, says "throws an error" once
  • Node.js: Cannot predict which properties present in failing calls
  • Most libraries don't document what errors they throw

Exception Types in JavaScript

  • Avoidable exceptions: logical errors in calling code (e.g., calling at(32) on empty array)
  • Unavoidable exceptions: network/system failures beyond programmer control
  • JavaScript culture lacks strongly typed exceptions
  • Consequence of language design - no first-class filtering mechanism for specific exceptions
  • Garbage collection handles cleanup, unlike other languages requiring explicit resource management
  • JavaScript allows returning different types from functions, reducing need for exceptions

Current Exception Handling Best Practices

  • Standard pattern: check instanceof TypeError, string conversion, else rethrow
  • TypeScript already provides strong typing for common error checks
  • Pattern matching in catch clauses proposed as TC39 feature
  • Multiple catch blocks with different error type checks

Barriers to Typed Exceptions

  • Default throw state problem: 100% of functions lack throws clauses
  • Must decide what unannotated functions do (throw nothing vs throw anything)
  • Either assumption breaks feature until all type definitions have accurate throw clauses
  • Assignability must account for throw information
  • Getters/setters can also throw
  • ES spec defines 400+ places where exceptions thrown
  • No clear distinction between avoidable/unavoidable exceptions

Conditions for Reconsideration

  • Widespread adoption of strong exception hierarchies in JS libraries
  • TC39 proposals for pattern matching in catch exceptions
  • Both would need to happen for TypeScript team to reconsider

Alternative Syntax Proposals

  • try [error, data] = await mightFail()
  • [error, data] = try await mightFail()
  • [error, data] = await mightFail()?
  • [error, data] ?= await mightFail()
  • Community preference leans toward try keyword variants
  • Concern about keyword resulting in tuple feeling strange
  • Variable definition syntax can be confusing when brain skips left side

Effect TS Implementation Example

  • Upload Thing backend uses Effect TS for proper error handling
  • Custom middleware with effect.gen forces yielding errors instead of throwing
  • Custom fetch error creation and handling
  • Micro (smaller Effect version) for promise handling
  • Proper error filtering and type management
  • Code barely looks like TypeScript but provides better error tracking
  • Team members Mark and Julius understand it well, writing better code