ClientErrorDelegate.swift 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. * Copyright 2019, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Foundation
  17. /// Delegate called when errors are caught by the client on individual HTTP/2 streams and errors in
  18. /// the underlying HTTP/2 connection.
  19. ///
  20. /// The intended use of this protocol is with `ClientConnection`. In order to avoid retain
  21. /// cycles, classes implementing this delegate **must not** maintain a strong reference to the
  22. /// `ClientConnection`.
  23. public protocol ClientErrorDelegate: class {
  24. /// Called when the client catches an error.
  25. ///
  26. /// - Parameters:
  27. /// - error: The error which was caught.
  28. /// - file: The file where the error was raised.
  29. /// - line: The line within the file where the error was raised.
  30. func didCatchError(_ error: Error, file: StaticString, line: Int)
  31. }
  32. /// A `ClientErrorDelegate` which logs errors only in debug builds.
  33. public class DebugOnlyLoggingClientErrorDelegate: ClientErrorDelegate {
  34. public static let shared = DebugOnlyLoggingClientErrorDelegate()
  35. private init() { }
  36. public func didCatchError(_ error: Error, file: StaticString, line: Int) {
  37. debugOnly {
  38. print("[grpc-client][\(Date())] error: \(error), file: \(file), line: \(line)")
  39. }
  40. }
  41. }
  42. /// A utility function that runs the body code only in debug builds, without emitting compiler
  43. /// warnings.
  44. ///
  45. /// This is currently the only way to do this in Swift: see
  46. /// https://forums.swift.org/t/support-debug-only-code/11037 for a discussion.
  47. internal func debugOnly(_ body: () -> Void) {
  48. assert({ body(); return true }())
  49. }