这是自定义错误的预期行为吗?

Is this intended behaviour of custom errors?

我目前正在重制 ES2015 五年前的 maze package。我正在创建一个名为 LengthError 的自定义错误,如果 Function 类型的参数没有指定长度,将抛出该错误。我只想知道这是否是预期的行为,因为我在本地 运行,或者这是否会在其他人可能使用此功能时延续到生产环境?

错误:

LengthError: Argument 'adjacent' must be of length 2
/home/runner/maze/index.ts:6
      throw new LengthError('Argument \'adjacent\' must be of length 2')
            ^

LengthError: Argument 'adjacent' must be of length 2
    at null.generate (/home/runner/maze/index.ts:6:13)
    at Object.<anonymous> (/home/runner/maze/index.ts:37:1)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:17:47

index.ts:

import { LengthError } from './errors';

export default function generate(nodes: number[], adjacent: Function, choose: Function) {
  if (adjacent.length !== 2) {
    try {
      throw new LengthError('Argument \'adjacent\' must be of length 2')
    } catch(e: any) {
      console.error(e.name + ': ' + e.message + '\n' + e.stack)
    }
  }
  let node: number = choose(nodes);
  let stack = [node];
  let maze = new Map();
  for (node of nodes) {
    maze.set(node, []);
  }
  
  while (node) {
    let neighbors = nodes.filter(other => !maze.get(other).length && adjacent(node, other));
    
    if (neighbors.length) {
      const neighbor = choose(neighbors);
      maze.get(node).push(neighbor);
      maze.get(neighbor).push(node);
      stack.unshift(neighbor);
      node = neighbor;
    } else {
      stack.shift();
      node = stack[0];
    }
  }

  
  return maze;
}

generate([], function a() {}, function b() {});

errors.ts:

class LengthError extends Error {
  constructor(message: string) {
    super(message);
    this.message = message;
    this.name = "LengthError";
  }
}

export { LengthError };

同样,这段代码是否会在生产中显示类似的错误(自定义错误显示两次),它会指向我文件中的同一行吗?

I just want to know if this is the intended behaviour because I am running this locally, or if this will carry over to production for when others might use this function?

是的,这就是它在本地和生产中的工作方式。当使用 try/catch.

出现未捕获的异常时,这就是 nodejs 所做的

当你抛出错误时,你应该在其他地方有代码来捕获它们并将它们变成所需的行为。

在错误信息中,第一行是错误的陈述。第二组行是“堆栈跟踪”,显示代码中的何处起源,包括错误发生时的当前调用堆栈。

请注意,在捕获异常的代码中,您可能希望记录异常,甚至可能记录跟踪跟踪,然后以某种对您的应用程序有意义的方式“处理”错误(例如 return user-friendly 错误消息或 API、return 一些已记录的 API 错误或 http 请求 return 4xx 或 5xx 错误状态) .