企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
强烈建议你在发生错误的时候用这些名字来保持和Node核心以及Node插件的一致。这些大部分不会和某个给定的异常对应,但是出现疑问的时候,你应该包含任何看起来有用的信息,即从编程上也从自定义的错误消息上。【表】。 | Property name | Intended use | | --- | --- | | localHostname | the local DNS hostname (e.g., that you're accepting connections at) | | localIp | the local IP address (e.g., that you're accepting connections at) | | localPort | the local TCP port (e.g., that you're accepting connections at) | | remoteHostname | the DNS hostname of some other service (e.g., that you tried to connect to) | | remoteIp | the IP address of some other service (e.g., that you tried to connect to) | | remotePort | the port of some other service (e.g., that you tried to connect to) | | path | the name of a file, directory, or Unix Domain Socket (e.g., that you tried to open) | | srcpath | the name of a path used as a source (e.g., for a rename or copy) | | dstpath | the name of a path used as a destination (e.g., for a rename or copy) | | hostname | a DNS hostname (e.g., that you tried to resolve) | | ip | an IP address (e.g., that you tried to reverse-resolve) | | propertyName | an object property name, or an argument name (e.g., for a validation error) | | propertyValue | an object property value (e.g., for a validation error) | | syscall | the name of a system call that failed | | errno | the symbolic value of errno (e.g., "ENOENT"). Do not use this for errors that don't actually set the C value of errno.Use "name" to distinguish between types of errors. | ## 脚注 1. 人们有的时候会这么写代码,他们想要在出现异步错误的时候调用 callback 并把错误作为参数传递。他们错误地认为在自己的回调函数(传递给 `doSomeAsynchronousOperation` 的函数)里`throw` 一个异常,会被外面的catch代码块捕获。`try/catch`和异步函数不是这么工作的。回忆一下,异步函数的意义就在于被调用的时候`myApiFunc`函数已经返回了。这意味着try代码块已经退出了。这个回调函数是由Node直接调用的,外面并没有try的代码块。如果你用这个反模式,结果就是抛出异常的时候,程序崩溃了。 2. 在JavaScript里,抛出一个不属于Error的参数从技术上是可行的,但是应该被避免。这样的结果使获得调用堆栈没有可能,代码也无法检查”name“属性,或者其它任何能够说明哪里有问题的属性。 3. 操作失败和程序员的失误这一概念早在NodeJS之前就已经存在存在了。不严格地对应者Java里的checked和unchecked异常,虽然操作失败被认为是无法避免的,比如 OutOfMemeoryError,被归为uncheked异常。在C语言里有对应的概念,普通异常处理和使用断言。维基百科上关于断言的的文章也有关于什么时候用断言什么时候用普通的错误处理的类似的解释。 4. 如果这看起来非常具体,那是因为我们在产品环境中遇到这样过这样的问题。这真的很可怕。 **本文由[OneAPM](http://www.oneapm.com/?hmsr=media&hmmd=&hmpl=&hmkw=&hmci=)工程师编译并整理 ,想阅读更多技术文章,请访问OneAPM[官方技术博客](http://code.oneapm.com/?hmsr=media&hmmd=&hmpl=&hmkw=&hmci=)。**