ClientErrorDelegate.swift 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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: AnyObject, GRPCPreconcurrencySendable {
  25. /// Called when the client catches an error.
  26. ///
  27. /// - Parameters:
  28. /// - error: The error which was caught.
  29. /// - logger: A logger with relevant metadata for the RPC or connection the error relates to.
  30. /// - file: The file where the error was raised.
  31. /// - line: The line within the file where the error was raised.
  32. func didCatchError(_ error: Error, logger: Logger, file: StaticString, line: Int)
  33. }
  34. extension ClientErrorDelegate {
  35. /// Calls ``didCatchError(_:logger:file:line:)`` with appropriate context placeholders when no
  36. /// context is available.
  37. internal func didCatchErrorWithoutContext(_ error: Error, logger: Logger) {
  38. self.didCatchError(error, logger: logger, file: "<unknown>", line: 0)
  39. }
  40. }
  41. /// A ``ClientErrorDelegate`` which logs errors.
  42. public final class LoggingClientErrorDelegate: ClientErrorDelegate {
  43. /// A shared instance of this class.
  44. public static let shared = LoggingClientErrorDelegate()
  45. public init() {}
  46. public func didCatchError(_ error: Error, logger: Logger, file: StaticString, line: Int) {
  47. logger.error(
  48. "grpc client error",
  49. metadata: [MetadataKey.error: "\(error)"],
  50. source: "GRPC",
  51. file: "\(file)",
  52. function: "<unknown>",
  53. line: UInt(line)
  54. )
  55. }
  56. }