实现说明
真正干活的是类 ConfigError和函数 parsePort、loadConfig,其余都是接线。
文件的主干是一个循环——while (current instanceof Error)。ConfigError 是守卫的信号——在分支处抛出,任何半成品工作之前。
使用要点
- 每一步打印都带着自己的标签:
root cause reached。
常见问题
这段代码会校验输入吗?
代码会抛出 ConfigError。请在调用点处理,或有意让它向上传播。
运行前要先安装什么?
什么都不用额外装——运行时自带了代码所需的一切。 文件在加载时定义 parsePort、loadConfig。
主要签名是 function parsePort(raw: string)
核心语句
throw new ConfigError('failed to load config', { cause: error });
throw new ConfigError('invalid port: ' + raw);
return parsePort(raw);
代码示例
class ConfigError extends Error {
constructor(message: string, options?: ErrorOptions) {
super(message, options);
this.name = 'ConfigError';
}
}
function parsePort(raw: string): number {
const port = Number(raw);
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new ConfigError('invalid port: ' + raw);
}
return port;
}
function loadConfig(raw: string): number {
try {
return parsePort(raw);
} catch (error) {
// cause 保留底层异常,外层只补充自己的上下文
throw new ConfigError('failed to load config', { cause: error });
}
}
try {
loadConfig('eighty');
} catch (error) {
let current: unknown = error;
while (current instanceof Error) {
console.log(current.name + ':', current.message);
current = current.cause;
}
console.log('root cause reached');
}