GRPCError.swift 8.2 KB

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