GRPCError.swift 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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 wrappedError: 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 (wrappedError as? GRPCStatusTransformable)?.asGRPCStatus() ?? .processingError
  31. }
  32. private init(_ error: Error, origin: Origin, file: StaticString, line: Int) {
  33. self.wrappedError = 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 ":status" header was not a valid HTTP status.
  84. case invalidHTTPStatus(HTTPResponseStatus?)
  85. /// The ":status" header was not a valid HTTP status but a "grpc-status" header with a valid
  86. /// value was present.
  87. case invalidHTTPStatusWithGRPCStatus(GRPCStatus)
  88. /// The call was cancelled by the client.
  89. case cancelledByClient
  90. /// It was not possible to deserialize the response protobuf.
  91. case responseProtoDeserializationFailure
  92. /// It was not possible to serialize the request protobuf.
  93. case requestProtoSerializationFailure
  94. /// More than one response was received for a unary-response call.
  95. case responseCardinalityViolation
  96. /// The call deadline was exceeded.
  97. case deadlineExceeded(GRPCTimeout)
  98. /// The protocol negotiated via ALPN was not valid.
  99. case applicationLevelProtocolNegotiationFailed
  100. /// The "content-type" header was invalid.
  101. case invalidContentType
  102. }
  103. /// An error which should be thrown by either the client or server.
  104. public enum GRPCCommonError: Error, Equatable {
  105. /// An invalid state has been reached; something has gone very wrong.
  106. case invalidState(String)
  107. /// Compression was indicated in the "grpc-message-encoding" header but not in the gRPC message compression flag, or vice versa.
  108. case unexpectedCompression
  109. /// The given compression mechanism is not supported.
  110. case unsupportedCompressionMechanism(String)
  111. }
  112. extension GRPCServerError: GRPCStatusTransformable {
  113. public func asGRPCStatus() -> GRPCStatus {
  114. // These status codes are informed by: https://github.com/grpc/grpc/blob/master/doc/statuscodes.md
  115. switch self {
  116. case .unimplementedMethod(let method):
  117. return GRPCStatus(code: .unimplemented, message: "unknown method \(method)")
  118. case .base64DecodeError:
  119. return GRPCStatus(code: .internalError, message: "could not decode base64 message")
  120. case .requestProtoDeserializationFailure:
  121. return GRPCStatus(code: .internalError, message: "could not parse request proto")
  122. case .responseProtoSerializationFailure:
  123. return GRPCStatus(code: .internalError, message: "could not serialize response proto")
  124. case .noRequestsButOneExpected:
  125. return GRPCStatus(code: .unimplemented, message: "request cardinality violation; method requires exactly one request but client sent none")
  126. case .tooManyRequests:
  127. return GRPCStatus(code: .unimplemented, message: "request cardinality violation; method requires exactly one request but client sent more")
  128. case .serverNotWritable:
  129. return GRPCStatus.processingError
  130. }
  131. }
  132. }
  133. extension GRPCClientError: GRPCStatusTransformable {
  134. public func asGRPCStatus() -> GRPCStatus {
  135. switch self {
  136. case .HTTPStatusNotOk(let status):
  137. return GRPCStatus(code: status.grpcStatusCode, message: "\(status.code): \(status.reasonPhrase)")
  138. case .invalidHTTPStatus(let status):
  139. let code = status?.grpcStatusCode ?? .internalError
  140. let reason = status?.reasonPhrase ?? ""
  141. return GRPCStatus(code: code, message: "invalid HTTP status: \(reason)")
  142. case .invalidHTTPStatusWithGRPCStatus(let status):
  143. return status
  144. case .cancelledByClient:
  145. return GRPCStatus(code: .cancelled, message: "client cancelled the call")
  146. case .responseCardinalityViolation:
  147. return GRPCStatus(code: .unimplemented, message: "response cardinality violation; method requires exactly one response but server sent more")
  148. case .responseProtoDeserializationFailure:
  149. return GRPCStatus(code: .internalError, message: "could not parse response proto")
  150. case .requestProtoSerializationFailure:
  151. return GRPCStatus(code: .internalError, message: "could not serialize request proto")
  152. case .deadlineExceeded(let timeout):
  153. return GRPCStatus(code: .deadlineExceeded, message: "call exceeded timeout of \(timeout)")
  154. case .applicationLevelProtocolNegotiationFailed:
  155. return GRPCStatus(code: .invalidArgument, message: "failed to negotiate application level protocol")
  156. case .invalidContentType:
  157. return GRPCStatus(code: .internalError, message: "invalid 'content-type' header")
  158. }
  159. }
  160. }
  161. extension GRPCCommonError: GRPCStatusTransformable {
  162. public func asGRPCStatus() -> GRPCStatus {
  163. switch self {
  164. case .invalidState:
  165. return GRPCStatus.processingError
  166. case .unexpectedCompression:
  167. return GRPCStatus(code: .unimplemented, message: "compression was enabled for this gRPC message but not for this call")
  168. case .unsupportedCompressionMechanism(let mechanism):
  169. return GRPCStatus(code: .unimplemented, message: "unsupported compression mechanism \(mechanism)")
  170. }
  171. }
  172. }
  173. extension HTTPResponseStatus {
  174. /// The gRPC status code associated with the HTTP status code.
  175. ///
  176. /// See: https://github.com/grpc/grpc/blob/master/doc/http-grpc-status-mapping.md
  177. internal var grpcStatusCode: GRPCStatus.Code {
  178. switch self {
  179. case .badRequest:
  180. return .internalError
  181. case .unauthorized:
  182. return .unauthenticated
  183. case .forbidden:
  184. return .permissionDenied
  185. case .notFound:
  186. return .unimplemented
  187. case .tooManyRequests, .badGateway, .serviceUnavailable, .gatewayTimeout:
  188. return .unavailable
  189. default:
  190. return .unknown
  191. }
  192. }
  193. }