GRPCError.swift 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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 NIOHTTP1
  18. /// Wraps a gRPC error to provide contextual information about where it was thrown.
  19. public struct GRPCError: Error, GRPCStatusTransformable {
  20. public enum Origin { case client, server }
  21. /// The underlying error thrown by framework.
  22. public let error: Error
  23. /// The origin of the error.
  24. public let origin: Origin
  25. /// The file in which the error was thrown.
  26. public let file: StaticString
  27. /// The line number in the `file` where the error was thrown.
  28. public let line: Int
  29. public func asGRPCStatus() -> GRPCStatus {
  30. return (error as? GRPCStatusTransformable)?.asGRPCStatus() ?? GRPCStatus.processingError
  31. }
  32. private init(_ error: Error, origin: Origin, file: StaticString, line: Int) {
  33. self.error = error
  34. self.origin = origin
  35. self.file = file
  36. self.line = line
  37. }
  38. /// Creates a `GRPCError` which may only be thrown from the client.
  39. public static func client(_ error: GRPCClientError, file: StaticString = #file, line: Int = #line) -> GRPCError {
  40. return GRPCError(error, origin: .client, file: file, line: line)
  41. }
  42. /// Creates a `GRPCError` which was thrown from the client.
  43. public static func client(_ error: GRPCCommonError, file: StaticString = #file, line: Int = #line) -> GRPCError {
  44. return GRPCError(error, origin: .client, file: file, line: line)
  45. }
  46. /// Creates a `GRPCError` which may only be thrown from the server.
  47. public static func server(_ error: GRPCServerError, file: StaticString = #file, line: Int = #line) -> GRPCError {
  48. return GRPCError(error, origin: .server, file: file, line: line)
  49. }
  50. /// Creates a `GRPCError` which was thrown from the server.
  51. public static func server(_ error: GRPCCommonError, file: StaticString = #file, line: Int = #line) -> GRPCError {
  52. return GRPCError(error, origin: .server, file: file, line: line)
  53. }
  54. /// Creates a `GRPCError` which was may be thrown by either the server or the client.
  55. public static func common(_ error: GRPCCommonError, origin: Origin, file: StaticString = #file, line: Int = #line) -> GRPCError {
  56. return GRPCError(error, origin: origin, file: file, line: line)
  57. }
  58. public static func unknown(_ error: Error, origin: Origin) -> GRPCError {
  59. return GRPCError(error, origin: origin, file: "<unknown>", line: 0)
  60. }
  61. }
  62. /// An error which should only be thrown by the server.
  63. public enum GRPCServerError: Error, Equatable {
  64. /// The RPC method is not implemented on the server.
  65. case unimplementedMethod(String)
  66. /// It was not possible to decode a base64 message (gRPC-Web only).
  67. case base64DecodeError
  68. /// It was not possible to deserialize the request protobuf.
  69. case requestProtoDeserializationFailure
  70. /// It was not possible to serialize the response protobuf.
  71. case responseProtoSerializationFailure
  72. /// Zero requests were sent for a unary-request call.
  73. case noRequestsButOneExpected
  74. /// More than one request was sent for a unary-request call.
  75. case tooManyRequests
  76. /// The server received a message when it was not in a writable state.
  77. case serverNotWritable
  78. }
  79. /// An error which should only be thrown by the client.
  80. public enum GRPCClientError: Error, Equatable {
  81. /// The response status was not "200 OK".
  82. case HTTPStatusNotOk(HTTPResponseStatus)
  83. /// The call was cancelled by the client.
  84. case cancelledByClient
  85. /// It was not possible to deserialize the response protobuf.
  86. case responseProtoDeserializationFailure
  87. /// It was not possible to serialize the request protobuf.
  88. case requestProtoSerializationFailure
  89. /// More than one response was received for a unary-response call.
  90. case responseCardinalityViolation
  91. /// The call deadline was exceeded.
  92. case deadlineExceeded(GRPCTimeout)
  93. }
  94. /// An error which should be thrown by either the client or server.
  95. public enum GRPCCommonError: Error, Equatable {
  96. /// An invalid state has been reached; something has gone very wrong.
  97. case invalidState(String)
  98. /// Compression was indicated in the "grpc-message-encoding" header but not in the gRPC message compression flag, or vice versa.
  99. case unexpectedCompression
  100. /// The given compression mechanism is not supported.
  101. case unsupportedCompressionMechanism(String)
  102. }
  103. extension GRPCServerError: GRPCStatusTransformable {
  104. public func asGRPCStatus() -> GRPCStatus {
  105. // These status codes are informed by: https://github.com/grpc/grpc/blob/master/doc/statuscodes.md
  106. switch self {
  107. case .unimplementedMethod(let method):
  108. return GRPCStatus(code: .unimplemented, message: "unknown method \(method)")
  109. case .base64DecodeError:
  110. return GRPCStatus(code: .internalError, message: "could not decode base64 message")
  111. case .requestProtoDeserializationFailure:
  112. return GRPCStatus(code: .internalError, message: "could not parse request proto")
  113. case .responseProtoSerializationFailure:
  114. return GRPCStatus(code: .internalError, message: "could not serialize response proto")
  115. case .noRequestsButOneExpected:
  116. return GRPCStatus(code: .unimplemented, message: "request cardinality violation; method requires exactly one request but client sent none")
  117. case .tooManyRequests:
  118. return GRPCStatus(code: .unimplemented, message: "request cardinality violation; method requires exactly one request but client sent more")
  119. case .serverNotWritable:
  120. return GRPCStatus.processingError
  121. }
  122. }
  123. }
  124. extension GRPCClientError: GRPCStatusTransformable {
  125. public func asGRPCStatus() -> GRPCStatus {
  126. switch self {
  127. case .HTTPStatusNotOk(let status):
  128. return GRPCStatus(code: .unknown, message: "server returned \(status.code) \(status.reasonPhrase)")
  129. case .cancelledByClient:
  130. return GRPCStatus(code: .cancelled, message: "client cancelled the call")
  131. case .responseCardinalityViolation:
  132. return GRPCStatus(code: .unimplemented, message: "response cardinality violation; method requires exactly one response but server sent more")
  133. case .responseProtoDeserializationFailure:
  134. return GRPCStatus(code: .internalError, message: "could not parse response proto")
  135. case .requestProtoSerializationFailure:
  136. return GRPCStatus(code: .internalError, message: "could not serialize request proto")
  137. case .deadlineExceeded(let timeout):
  138. return GRPCStatus(code: .deadlineExceeded, message: "call exceeded timeout of \(timeout)")
  139. }
  140. }
  141. }
  142. extension GRPCCommonError: GRPCStatusTransformable {
  143. public func asGRPCStatus() -> GRPCStatus {
  144. switch self {
  145. case .invalidState:
  146. return GRPCStatus.processingError
  147. case .unexpectedCompression:
  148. return GRPCStatus(code: .unimplemented, message: "compression was enabled for this gRPC message but not for this call")
  149. case .unsupportedCompressionMechanism(let mechanism):
  150. return GRPCStatus(code: .unimplemented, message: "unsupported compression mechanism \(mechanism)")
  151. }
  152. }
  153. }