附錄:Error 對象屬性命名約定

2018-02-24 16:16 更新

強烈建議你在發(fā)生錯誤的時候用這些名字來保持和Node核心以及Node插件的一致。這些大部分不會和某個給定的異常對應,但是出現(xiàn)疑問的時候,你應該包含任何看起來有用的信息,即從編程上也從自定義的錯誤消息上?!颈怼俊?/p>

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. 人們有的時候會這么寫代碼,他們想要在出現(xiàn)異步錯誤的時候調(diào)用 callback 并把錯誤作為參數(shù)傳遞。他們錯誤地認為在自己的回調(diào)函數(shù)(傳遞給?doSomeAsynchronousOperation?的函數(shù))里throw?一個異常,會被外面的catch代碼塊捕獲。try/catch和異步函數(shù)不是這么工作的。回憶一下,異步函數(shù)的意義就在于被調(diào)用的時候myApiFunc函數(shù)已經(jīng)返回了。這意味著try代碼塊已經(jīng)退出了。這個回調(diào)函數(shù)是由Node直接調(diào)用的,外面并沒有try的代碼塊。如果你用這個反模式,結(jié)果就是拋出異常的時候,程序崩潰了。

  2. 在JavaScript里,拋出一個不屬于Error的參數(shù)從技術(shù)上是可行的,但是應該被避免。這樣的結(jié)果使獲得調(diào)用堆棧沒有可能,代碼也無法檢查”name“屬性,或者其它任何能夠說明哪里有問題的屬性。

  3. 操作失敗和程序員的失誤這一概念早在NodeJS之前就已經(jīng)存在存在了。不嚴格地對應者Java里的checked和unchecked異常,雖然操作失敗被認為是無法避免的,比如 OutOfMemeoryError,被歸為uncheked異常。在C語言里有對應的概念,普通異常處理和使用斷言。維基百科上關(guān)于斷言的的文章也有關(guān)于什么時候用斷言什么時候用普通的錯誤處理的類似的解釋。

  4. 如果這看起來非常具體,那是因為我們在產(chǎn)品環(huán)境中遇到這樣過這樣的問題。這真的很可怕。

本文由OneAPM工程師編譯并整理 ,想閱讀更多技術(shù)文章,請訪問OneAPM官方技術(shù)博客。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號