我在看 net/http 和 crypto/x509我想知道哪種方法更好,為什么。net/http/http.go 使用字符串:// HTTP request parsing errors.type ProtocolError struct { ErrorString string}func (err *ProtocolError) Error() string { return err.ErrorString }var ( ErrHeaderTooLong = &ProtocolError{"header too long"} ErrShortBody = &ProtocolError{"entity body too short"} ErrNotSupported = &ProtocolError{"feature not supported"} ErrUnexpectedTrailer = &ProtocolError{"trailer header without chunked transfer encoding"} ErrMissingContentLength = &ProtocolError{"missing ContentLength in HEAD response"} ErrNotMultipart = &ProtocolError{"request Content-Type isn't multipart/form-data"} ErrMissingBoundary = &ProtocolError{"no multipart boundary param in Content-Type"})crypto/x509/verify.go 使用整數:type InvalidReason intconst ( TooManyIntermediates IncompatibleUsage)type CertificateInvalidError struct { Cert *Certificate Reason InvalidReason}func (e CertificateInvalidError) Error() string { switch e.Reason { case TooManyIntermediates: return "x509: too many intermediates for path length constraint" case IncompatibleUsage: return "x509: certificate specifies an incompatible key usage" } return "x509: unknown error"}
1 回答

慕田峪4524236
TA貢獻1875條經驗 獲得超5個贊
兩種用法都很好,但這取決于您的需求。
如果您發現將附加數據附加到錯誤消息中未顯示的錯誤很有用,那么 中的方法crypto/x509
更可取。
但我認為在大多數情況下,包中的簡單錯誤字符串errors
就足夠了。
編輯
一個錯誤可以有不同的“屬性”:
描述
Error() 方法應該返回一個簡短的描述錯誤消息
可識別
通過讓包導出它可能返回的不同錯誤,您可以識別它們。這可以io
通過導出相同類型的初始化錯誤變量來完成:
if err == io.EOF { ... } // That's easy
或者像在encoding/json
包中導出不同的錯誤類型:
if mErr, ok := err.(*json.MarshalerError); ok { ... } // That's fairly easy
或者像他們在crypto/x509
包中所做的那樣,通過導出不同的原因(錯誤代碼):
if e, ok := err.(x509.CertificateInvalidError); ok && e.Reason == x509.Expired { ... } // Well, it works
唯一錯誤代碼
如果由于協議規范錯誤應該具有特定代碼,則可以將這些代碼嵌入到錯誤變量中。該crypto/x509
包可能用于此目的,即使情況可能并非如此。
但是說到如何解決它,我認為沒有最好的方法,也沒有任何明確的慣用方法。上面的示例向您展示了在標準庫中執行此操作的方法以及執行此操作的方式。隨你挑。
.. 但也許不使用 switch 語句。
- 1 回答
- 0 關注
- 197 瀏覽
添加回答
舉報
0/150
提交
取消