強烈建議你在發生錯誤的時候用這些名字來保持和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=)。**