Tip
You can test the runtime aspect of this proposal and its ergonomics today! Install our reference Result class implementation from NPM:
const result = try JSON.parse(input)
// Can be destructured
const { ok, error, value } = try await fetch("/api/users")
const [ok, fetchErr, res] = try fs.readFileSync("data.txt")This proposal addresses the ergonomic challenges of managing multiple, often nested, try/catch blocks necessary for handling operations that may fail at various points.
The try block needlessly encloses the protected code in a block. This often prevents straightforward const assignment patterns and can reduce readability through additional nesting. The catch (error) {} branch is usually where control-flow divergence happens, while the successful path is often linear.
The solution is to add a try <expression> operator, a syntax similar to await <expression>, which catches any error that occurs when executing its expression and returns it as a value to the caller.
JavaScript has no existing equivalent for in-place exception-to-value conversion without using executor callback arguments, which force code to cross function boundaries and create closures.
- Status
- Authors
- Try/Catch Is Not Enough
- Caller's Approach
- Result as a Return Type
- Try Operator
- Result Class
- Interop and Realms
- What This Proposal Does Not Aim to Solve
- Why Not
dataFirst? - The Need for an
okValue - A Case for Syntax
- Why This Belongs in the Language
- Evidence Plan
- Help Us Improve This Proposal
- Inspiration
- License
Stage: 0
Champion: Actively looking for one
For more information see the TC39 proposal process.
The try {} block introduces additional block scoping around non-exceptional flow. Unlike loops or conditionals, it does not represent a distinct program state that must be isolated.
On the other hand, the catch {} block is genuine alternate control flow, making its scoping relevant.
Since catch explicitly handles exceptions, encapsulating exception-handling logic in a dedicated block makes sense. In many cases, however, the successful flow does not benefit from extra lexical nesting.
Consider a simple function like this:
function getPostInfo(session, postSlug, cache, db) {
const user = cache.getUser(session.userId)
const post = db.selectPost(postSlug, user)
const comments = db.selectComments(post.id, user)
return { post, comments }
}But production code is rarely this clean. Error handling quickly forces a messier structure:
function getPostInfo(session, postSlug, cache, db) {
let user
// Requires a dedicated error handler
try {
user = cache.getUser(session.userId)
} catch (error) {
otel.capture(error, Operations.GET_SELF)
session.logout()
throw new Error("Invalid session")
}
// No recovery if selectPost fails
try {
const post = db.selectPost(postSlug, user)
let comments = []
// The post must still be returned even if fetching comments fails
try {
comments = db.selectComments(post.id, user)
} catch (error) {
otel.capture(error, Operations.JOIN_POST_COMMENTS)
}
return { post, comments }
} catch (error) {
otel.capture(error, Operations.GET_POST)
throw new Error("Could not get post")
}
}In this example, the try blocks primarily introduce additional nesting.
Instead, using the proposed try operator simplifies the function:
function getPostInfo(session, postId, cache, db) {
const [userOk, userErr, user] = try cache.getUser(session.userId)
// Requires a dedicated error handler
if (!userOk) {
session.logout()
otel.capture(userErr, Operations.GET_SELF)
throw new Error("Invalid session")
}
const [postOk, postErr, post] = try db.selectPost(postId, user)
// No recovery if selectPost fails
if (!postOk) {
otel.capture(postErr, Operations.GET_POST)
throw new Error("Could not get post")
}
const [commentsOk, commentsErr, comments = []] = try db.selectComments(post.id, user)
// The post must still be returned even if fetching comments fails
if (!commentsOk) {
otel.capture(commentsErr, Operations.JOIN_POST_COMMENTS)
}
return { post, comments }
}This approach often improves readability by cleanly separating the happy path from error handling.
Control flow remains linear, making it easier to follow, while only exception paths require explicit branching.
The result is a more structured, maintainable function where failures are handled concisely without unnecessary indentation.
JavaScript has evolved over decades, with countless libraries and codebases built on top of one another. Any new feature that does not consider compatibility with existing code risks negatively impacting its adoption, as refactoring functional, legacy code simply to accommodate a new feature is often an unjustifiable cost.
With that in mind, improvements in error handling can be approached in two ways:
-
At the caller's level:
try { const value = work() } catch (error) { console.error(error) }
-
At the callee's level:
function work() { try { // Performs some operation return { ok: true, value } } catch (error) { return { ok: false, error } } }
Both approaches achieve the same goal, but the second one requires refactoring implementations into a new format. Languages like Go and Rust use callee-level result values from the start. Introducing that model later in JavaScript has a different compatibility and adoption profile.
This proposal accounts for this by moving the transformation of errors into values to the caller level, preserving the familiar semantics and placement of try/catch. This approach ensures backward compatibility with existing code.
For platforms like Node.js and widely used libraries, compatibility costs are high. As a result, a callee-based transition for APIs like fetch or fs.readFile is unlikely in practice because it would require broad refactoring across existing codebases.
Ironically, these are precisely the kinds of functions where improved error handling is most needed.
One of the Result principles is to wrap at the top, not throughout the stack. Returning Result from functions is possible, but often unnecessary.
Consider a call chain where getUser() calls db.select(), which calls db.connect(). If none return Result, the caller can simply write:
const result = try getUser(id)This single try captures any error thrown anywhere in the chain. Compare this to returning Result throughout the stack:
// Every function must check and forward errors.
function getUser(id) {
const connResult = db.connect()
if (!connResult.ok) {
return connResult
}
const userResult = db.select(connResult.value, id)
if (!userResult.ok) {
return userResult
}
return Result.ok(normalize(userResult.value))
}Result-returning functions cannot be freely composed with throw-based functions without explicit unwrapping at each boundary. This repetitive if (!result.ok) { return result } forwarding is reminiscent of Go's if err != nil { return err }. Rob Pike's "Errors are values" addresses this: the solution is not more syntax sugar (a try?-like operator), but recognizing that errors are values that can be programmed creatively. In many cases, this repetition is a useful signal that the code may benefit from restructuring rather than new syntax.
Returning Result can force callers to acknowledge errors in ways JSDoc cannot. However, the function coloring tradeoff often outweighs this benefit. When acknowledgement is not required, a single try at the top of the call stack achieves the same safety without coloring every function in the chain.
The try operator is designed to coexist with throw, not replace it. Following the caller's approach, functions typically throw and let callers decide how to handle errors. Returning Result can still make sense when forcing acknowledgement is more important than minimizing cross-boundary error-conversion boilerplate.
Mixed patterns (Result return + throw) may exist in practice, but this proposal treats them as unusual boundaries rather than the default composition path (see No Flattening).
For further discussion, see GitHub Issue #92.
The try operator consists of the try keyword followed by an expression. It results in an instance of the Result.
All of its usages are just a combination of the above said rules.
// wraps the result of `something()` in a Result
const a = try something()
// Result can be destructured as an object
const { ok, error, value } = try something()
// Result is also iterable
const [ok, err, val] = try something()
// Result still is iterable
const [[ok, err, val]] = [try something()]
// Result[]
array.map(fn => try fn())
// yields Result
yield try something()
// Result<T> where T is the argument of iterator().next(arg: T) but also captures
// any error thrown by something()
try yield something()
// Result<Awaited<ReturnType<typeof something>>>
try await something()
// Catches potential TypeError: Right-hand side of 'instanceof' is not an object
try (a instanceof b)
// Result<boolean> instanceof boolean
(try a) instanceof Result
// Result<Result<Result<Result<Result<number>>>
const a = try (try (try (try (try 1))))const result = try expressionThis is "equivalent" to:
let _result
try {
_result = Result.ok(expression)
} catch (error) {
_result = Result.error(error)
}
const result = _resultSimilar to void, typeof, yield, and new:
array.map((fn) => try fn()).filter((result) => result.ok)const result = try data?.someProperty.anotherFunction?.(await someData()).andAnotherOne()This is "equivalent" to:
let _result
try {
_result = Result.ok(
data?.someProperty.anotherFunction?.(await someData()).andAnotherOne(),
)
} catch (error) {
_result = Result.error(error)
}
const result = _resultconst result = try await fetch("https://arthur.place")Which is only valid in async contexts and equates to:
let _result
try {
_result = Result.ok(await fetch("https://arthur.place"))
} catch (error) {
_result = Result.error(error)
}
const result = _resultconst result = try throw new Error("Something went wrong") // Syntax error!
const result = try using resource = new Resource() // Syntax error!This is because their "equivalent" would also result in a syntax error:
let _result
try {
_result = Result.ok(throw new Error("Something went wrong")) // Syntax error!
} catch (error) {
_result = Result.error(error)
}
const result = _resultA detailed discussion about this topic is available at GitHub Issue #54 for those interested.
The try operator converts any ECMAScript throw produced while evaluating its operand expression into a Result.error(...) value:
const [ok, error, result] = try some.thing()For example:
- If
someisundefined. - If
thingis not a function. - If accessing the
thingproperty onsomethrows an error. - Any other exception that can arise on that line of code.
All these thrown values are captured and encapsulated in the returned Result.
As with other JavaScript constructs, host-level fatal termination conditions are out of scope.
When using try with an object literal, the literal must be enclosed in parenthesis:
const result = try ({ data: await work() })This behavior mirrors how JavaScript differentiates blocks and object literals:
{ a: 1 } // empty block with a label
({ a: 1 }) // object with a key `a` and a number `1`A detailed discussion about this topic is available at GitHub Issue #55 for those interested.
In scenarios where the successful result of an operation is not needed, it can be safely ignored:
function work() {
try fs.unlinkSync("temp.txt")
}This behavior aligns with common patterns, such as using await on asynchronous operations where the result is not utilized:
await fs.promises.unlink("temp.txt")While it is valid to ignore the result, tools like TypeScript ESLint may introduce similar rules, such as no-floating-promises, to encourage developers to explicitly indicate that the result is being ignored. A common workaround to provide a visual cue is to use void alongside try:
function work() {
// This approach works without modification and provides a clear hint
void try fs.unlinkSync("temp.txt")
}Ignoring a Result should be treated as an explicit choice. In critical code paths, prefer handling or rethrowing to avoid accidentally swallowing failures.
Wrapping a Result-returning function with try yields Result<Result<T>>, not a flattened Result<T>.
This is intentional. Functions that return Result and also throw do exist in practice, but this proposal does not optimize for that pattern. The nested shape marks an unusual boundary: either try is unnecessary (the callee already returns Result), or the callee contract is mismatched (for example, it declares Result<T> but might throw). The rationale is not that Result-returning functions can never throw. It is that the operator should not silently normalize mixed channels.
If this becomes a pain point, future proposals could introduce Result.flatten() or .unwrap() methods. By contrast, automatic flattening would be difficult to remove later without compatibility risk.
When nested Result appears repeatedly, it usually indicates a boundary mismatch. Prefer picking one error channel per boundary and normalizing explicitly.
This proposal keeps try expression-oriented. At Stage 0, the core goal is to validate ergonomics and semantics before final grammar tuning, but the intended parsing model is straightforward:
tryapplies to a single operand expression, similar in spirit to other expression-position operators.try await expris parsed astry (await expr).- Parentheses disambiguate object literals and can always be used to make intent explicit.
- Existing
try { ... } catch { ... }statement form is unchanged.
As the proposal advances, this section will be replaced by fully normative grammar and precedence text.
This operator is intentionally small and does not replace all error-handling patterns.
try fetch()is not the same astry await fetch(). Rejections are caught when awaited.try <expression>is not a substitute fortry/finallywhen cleanup must always run.- Ignoring a
Resultcan hide failures if done carelessly. - Catching all throws at expression level may also catch programmer mistakes (for example
TypeError) unless code distinguishes and rethrows. - For shared policies (global retries, framework boundaries, platform-level telemetry), handling may belong at a higher boundary.
The try operator evaluates an expression and returns an instance of the Result class, which encapsulates the outcome of the operation.
To validate the ergonomics and utility of this proposal, a spec-compliant, runtime-only implementation of the Result class has been published to npm as the try package. This package provides a t() function that serves as a polyfill for the try operator's runtime behavior, allowing developers to experiment with the core pattern.
import { t } from "try"
const [ok, err, val] = await t(fetch, "https://arthur.place")You can check the published package at npmjs.com/package/try or github.com/arthurfiorette/try and contribute to its development.
A Result instance always contains a boolean ok property that indicates the outcome.
- If
okistrue, the instance also has avalueproperty containing the successful result. - If
okisfalse, it has anerrorproperty containing the thrown exception.
Crucially, a success result does not have an error property, and a failure result does not have a value property. This allows for reliable checks like 'error' in result.
const result = try something()
if (result.ok) {
console.log(result.value)
} else {
console.error(result.error)
}Since Result is a regular object, it supports object destructuring:
const { ok, error, value: user } = try User.parse(myJson)Result instances are also iterable, yielding their state in the order [ok, error, value]. This is particularly useful when combining multiple results, as positional destructuring allows easy renaming:
const [userOk, userErr, user] = try User.parse(myJson)
const [postOk, postErr, post] = try db.selectPost(postId, user)Both forms consume the same Result object. Object destructuring accesses named properties, while iterable destructuring enables positional renaming when multiple results are in scope.
While the try operator is the primary source of Result instances, they can also be created manually using static methods. This is useful for testing or for bridging with APIs that do not use exceptions.
// Create a successful result
const success = Result.ok(42)
// Create a failure result
const failure = Result.error(new Error("Operation failed"))It also includes a static Result.try() method, which serves as the runtime foundation for the try operator. This method wraps a function call, catching any synchronous exceptions or asynchronous rejections and returning a Result or Promise<Result>, respectively.
The proposed try expression syntax is essentially an ergonomic improvement over the more verbose Result.try(() => expression), removing the need for a function wrapper.
This proposal introduces a shared error-outcome value intended to work reliably across boundaries.
At Stage 0, the interoperability goals are:
- Cross-realm friendliness: values produced in one realm (for example iframe/vm contexts) should still be recognizable as
Resultin another. - Stable detection: developers should not have to rely exclusively on
instanceofchecks that can be realm-sensitive. - Predictable shape:
okis always present, with mutually exclusivevalueanderrorfields.
The exact branding and detection details are expected to be finalized in later stages, together with committee feedback on best cross-realm practices.
The throw statement in JavaScript can throw any type of value. This proposal does not impose nor propose any kind of safety around error handling.
- No generic error type for the proposed Result class will be added.
- No catch branching based on error type will be added. See GitHub Issue #43 for more information.
- No way to annotate a callable to specify the error type it throws will be added.
For more information, also see microsoft/typescript#13219.
While this proposal facilitates error handling, it does not automatically handle errors for you. You will still need to write the necessary code to manage errors the proposal simply aims to make this process easier and more consistent.
In Go, the convention is to place the data variable first, and you might wonder why we don't follow the same approach in JavaScript. In Go, this is the standard way to call a function. However, in JavaScript, we already have the option to use const data = fn() and choose to ignore the error, which is precisely the issue this proposal seeks to address.
If someone is using a try statement, it is because they want to ensure they handle errors and avoid neglecting them. Placing the data first would undermine this principle by prioritizing the result over error handling.
// This line doesn't acknowledge the possibility of errors being thrown
const data = fn()
// It's easy to forget to add a second error parameter
const [data] = try fn()
// This approach gives all clues to the reader about the 2 possible states
const [ok, error, data] = try fn()If you want to suppress the error (which is different from ignoring the possibility of a function throwing an error), you can do the following:
// This suppresses a possible error (Ignores and doesn't re-throw)
const [ok, , data] = try fn()This approach is explicit and readable, as it acknowledges the possibility of an error while indicating that you do not care about it.
The above method, can also be written as:
let ok = true
let data
try {
data = fn()
} catch {
ok = false
}A detailed discussion about this topic is available at GitHub Issue #13 for those interested.
The idea of throw x doing anything other than throwing x is inherently flawed. Wrapping the error in an object disregards this principle and introduces unnecessary ambiguity.
Consider the following pseudocode, which might seem harmless but is actually risky:
function doWork() {
if (check) {
throw createException(Errors.SOMETHING_WENT_WRONG)
}
return work()
}
const [error, data] = try doWork()
if (!error) {
user.send(data)
}There is no guarantee that createException always returns an exception. Someone could even mistakenly write throw null or throw undefined, both of which are valid but undesired JavaScript code.
Even though such cases are uncommon, they can occur. The ok value is crucial to mitigate these runtime risks effectively.
For a more in-depth explanation of this decision, refer to GitHub Issue #30.
This proposal intentionally combines the try operator with the Result class because each part motivates the other. The try operator standardizes a common pattern for safely catching synchronous function calls (similar to how Promise .catch handles async rejections).
At Stage 0, this is presented as a design hypothesis to validate with feedback and real-world usage:
- Syntax-only is incomplete: it gives concise conversion but no shared standard outcome container.
- Runtime-only is incomplete: it gives a container but keeps conversion boilerplate and callback wrappers.
- Combined proposal is coherent: one expression form plus one standard shape.
It has been suggested that a runtime-only proposal for the Result class might face less resistance within the TC39 process. While this strategic viewpoint is understood, this proposal deliberately presents a unified feature. Separating the runtime from the syntax severs the solution from its motivating problem. It would ask the committee to standardize a Result object whose design is justified by a syntax that doesn't yet exist.
Without the try operator, the Result class is just one of many possible library implementations, not a definitive language feature. We believe the feature must be evaluated on its complete ergonomic and practical merits, which is only possible when the syntax and runtime are presented together.
A proposal doesn’t need to introduce a feature that is entirely impossible to achieve otherwise. In fact, most recent proposals primarily reduce the complexity of tasks that are already achievable by providing built-in conveniences.
The absence of a Result-like type and a standard pattern for safely wrapping function calls has led to ecosystem fragmentation. Multiple packages and private utilities attempt to fill this gap with different shapes and conventions. This leaves developers with a poor choice: risk adopting a library that may be abandoned, or contribute to the problem by creating yet another bespoke implementation.
Like earlier ergonomics proposals such as optional chaining (?.) and nullish coalescing (??), this proposal targets a recurring pattern that appears repeatedly in userland. Unlike those features, it also introduces a standard error-outcome container.
It also creates a shared foundation between developers and package authors. Everyone can rely on the same Result implementation without compatibility concerns. The goal is to end the fragmentation and establish a foundational tool for robust error handling.
Because this proposal is at Stage 0, proving the problem and tradeoffs has priority over fully frozen specification text. This section will evolve as the proposal gains a champion and advances, but the initial plan is to:
- Gather real examples of nested
try/catchin production JavaScript and show equivalenttry <expression>refactors. - Compare before/after readability in terms of nesting depth and branching structure.
- Classify where this operator prevents mistakes vs where it could hide mistakes if misused.
- Catalog existing tuple/result wrappers and incompatibilities to justify standardization value.
This proposal is in its early stages, and we welcome your input to help refine it. Please feel free to open an issue or submit a pull request with your suggestions.
Any contribution is welcome!
- This tweet from @LeaVerou
- The frequent oversight of error handling in JavaScript code.
- Effect TS Error Management
- The
tuple-itnpm package, which introduces a similar concept but modifies thePromiseandFunctionprototypes. - Szymon Wygnański for donating the
trypackage name on NPM to host the reference implementation of this proposal. - The first concept of this proposal, called "Safe Assignment Operator".
This proposal is licensed under the MIT License.