JavaScript中的错误链:使用Error.cause进行更清晰的调试

Error handling in JavaScript has always felt a bit chaotic. Throwing errors is easy, but tracing them back to the root cause? Not so much. That’s where the cause property comes in.

JavaScript中的错误处理一直感觉有点混乱。抛出错误很简单,但追溯到根本原因?就没那么简单了。这就是cause属性的用武之地。

The problem with traditional error handling

传统错误处理的问题

When you’re working with layered code (e.g., services calling services, wrapper functions, bubbling errors, etc.), it’s easy to lose track of what actually broke. Traditionally, you might write something like this:

当你处理分层代码时(例如,服务调用服务、包装函数、冒泡错误等),很容易失去对 实际 发生了什么的追踪。传统上,你可能会写这样的代码:

try { JSON.parse('{ bad json }');
} catch (err) { throw new Error('Something went wrong: ' + err.message);
}

Sure, you wrapped the error, but you’ve lost the original stack trace and error type.

当然,您包装了错误,但您失去了原始的堆栈跟踪和错误类型。

Introducing Error.cause

介绍 Error.cause

By using the cause parameter, you can preserve the original error cleanly:

通过使用 cause 参数,您可以干净地保留原始错误:

try { try { JSON.parse('{ bad json }'); } catch (err) { throw new Error('Something went wrong', { cause: err }); }
} catch (err) { console.error(err.stack); console.error('Caused by:', err.cause.stack);
}

Here’s what happens when you use Error.cause (notice how you can access both stack traces):

当你使用 Error.cause 时会发生以下情况(注意你可以访问两个堆栈跟踪):

Error: Something went wrong at ...
Caused by: SyntaxError: Unexpected token b in JSON at position 2 at JSON.parse (<anonymous>) at ...

Now you’re preserving the original error while surfacing a clear top-level message.

现在你可以在同时保留原始错误的情况下,呈现一个清晰的顶层消息。

What it looks like in practice

实际效果如何

function fetchUserData() { try { JSON.parse('{ broken: true }'); } catch (parseError) { throw new Error('Failed to fetch user data', { cause: parseError }); }
} try { fetchUserData();
} catch (err) { console.error(err.message); console.error(err.cause); console.error(err.cause instanceof SyntaxError); }

That’s pretty slick.

这真不错。

The cause property is non-enumerable by specification when passed through the Error constructor, so it won’t clutter logs or for...in loops u...

开通本站会员,查看完整译文。

Home - Wiki
Copyright © 2011-2025 iteam. Current version is 2.148.0. UTC+08:00, 2025-11-13 06:09
浙ICP备14020137号-1 $Map of visitor$