How to log Error in Swift

Issue #439

Use localizedDescription

We need to provide NSLocalizedDescriptionKey inside user info dictionary, otherwise the outputt string may not be what we want.

NSError

https://developer.apple.com/documentation/foundation/nserror/1414418-localizeddescription

A string containing the localized description of the error.
The object in the user info dictionary for the key NSLocalizedDescriptionKey. If the user info dictionary doesn’t contain a value for NSLocalizedDescriptionKey, a default string is constructed from the domain and code.

1
2
3
4
5
6
7
let error = NSError(domain: "com.onmyway133.MyApp", code: 2, userInfo: [
"status_code": 2,
"status_message": "not enough power"
])

error.localizedDescription
// "The operation couldn’t be completed. (com.onmyway133.MyApp error 2.)"

Error

https://developer.apple.com/documentation/swift/error/2292912-localizeddescription

Retrieve the localized description for this error.

1
2
3
4
5
6
7
enum AppError: Error {
case request
case invalid
}

AppError.request.localizedDescription
// "The operation couldn’t be completed. (MyApp.AppError error 0.)"

Use describing String

To have better control, we can have toString which prints closly to what we expect

1
2
3
4
5
6
7
8
9
10
11
extension Error {
func toString() -> String {
return String(describing: self)
}
}

AppError.request.toString()
// request

nsError.toString()
// Error Domain=com.onmyway133.MyApp Code=2 "(null)" UserInfo={status_message=not enough power, status_code=SwiftGRPC.StatusCode.powerRequired}

Comments