ClientErrorDelegate.swift 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. import Logging
  18. /// Delegate called when errors are caught by the client on individual HTTP/2 streams and errors in
  19. /// the underlying HTTP/2 connection.
  20. ///
  21. /// The intended use of this protocol is with `ClientConnection`. In order to avoid retain
  22. /// cycles, classes implementing this delegate **must not** maintain a strong reference to the
  23. /// `ClientConnection`.
  24. public protocol ClientErrorDelegate: class {
  25. /// Called when the client catches an error.
  26. ///
  27. /// - Parameters:
  28. /// - error: The error which was caught.
  29. /// - file: The file where the error was raised.
  30. /// - line: The line within the file where the error was raised.
  31. func didCatchError(_ error: Error, file: StaticString, line: Int)
  32. }
  33. /// A `ClientErrorDelegate` which logs errors only in debug builds.
  34. public class DebugOnlyLoggingClientErrorDelegate: ClientErrorDelegate {
  35. public static let shared = DebugOnlyLoggingClientErrorDelegate()
  36. private let logger = Logger(labelSuffix: "ClientErrorDelegate")
  37. private init() { }
  38. public func didCatchError(_ error: Error, file: StaticString, line: Int) {
  39. debugOnly {
  40. self.logger.error(
  41. "client error",
  42. metadata: [MetadataKey.error: "\(error)"],
  43. file: "\(file)",
  44. function: "<unknown>",
  45. line: UInt(line)
  46. )
  47. }
  48. }
  49. }
  50. /// A utility function that runs the body code only in debug builds, without emitting compiler
  51. /// warnings.
  52. ///
  53. /// This is currently the only way to do this in Swift: see
  54. /// https://forums.swift.org/t/support-debug-only-code/11037 for a discussion.
  55. internal func debugOnly(_ body: () -> Void) {
  56. assert({ body(); return true }())
  57. }