強(qiáng)烈建議你在發(fā)生錯(cuò)誤的時(shí)候用這些名字來(lái)保持和Node核心以及Node插件的一致。這些大部分不會(huì)和某個(gè)給定的異常對(duì)應(yīng),但是出現(xiàn)疑問(wèn)的時(shí)候,你應(yīng)該包含任何看起來(lái)有用的信息,即從編程上也從自定義的錯(cuò)誤消息上。【表】。
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. |
人們有的時(shí)候會(huì)這么寫(xiě)代碼,他們想要在出現(xiàn)異步錯(cuò)誤的時(shí)候調(diào)用 callback 并把錯(cuò)誤作為參數(shù)傳遞。他們錯(cuò)誤地認(rèn)為在自己的回調(diào)函數(shù)(傳遞給?doSomeAsynchronousOperation
?的函數(shù))里throw
?一個(gè)異常,會(huì)被外面的catch代碼塊捕獲。try/catch
和異步函數(shù)不是這么工作的。回憶一下,異步函數(shù)的意義就在于被調(diào)用的時(shí)候myApiFunc
函數(shù)已經(jīng)返回了。這意味著try代碼塊已經(jīng)退出了。這個(gè)回調(diào)函數(shù)是由Node直接調(diào)用的,外面并沒(méi)有try的代碼塊。如果你用這個(gè)反模式,結(jié)果就是拋出異常的時(shí)候,程序崩潰了。
在JavaScript里,拋出一個(gè)不屬于Error的參數(shù)從技術(shù)上是可行的,但是應(yīng)該被避免。這樣的結(jié)果使獲得調(diào)用堆棧沒(méi)有可能,代碼也無(wú)法檢查”name“屬性,或者其它任何能夠說(shuō)明哪里有問(wèn)題的屬性。
操作失敗和程序員的失誤這一概念早在NodeJS之前就已經(jīng)存在存在了。不嚴(yán)格地對(duì)應(yīng)者Java里的checked和unchecked異常,雖然操作失敗被認(rèn)為是無(wú)法避免的,比如 OutOfMemeoryError,被歸為uncheked異常。在C語(yǔ)言里有對(duì)應(yīng)的概念,普通異常處理和使用斷言。維基百科上關(guān)于斷言的的文章也有關(guān)于什么時(shí)候用斷言什么時(shí)候用普通的錯(cuò)誤處理的類似的解釋。
本文由OneAPM工程師編譯并整理 ,想閱讀更多技術(shù)文章,請(qǐng)?jiān)L問(wèn)OneAPM官方技術(shù)博客。
更多建議: