GRPCError.swift 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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. /// More than one request was sent for a unary-request call.
  73. case requestCardinalityViolation
  74. /// The server received a message when it was not in a writable state.
  75. case serverNotWritable
  76. }
  77. /// An error which should only be thrown by the client.
  78. public enum GRPCClientError: Error, Equatable {
  79. /// The response status was not "200 OK".
  80. case HTTPStatusNotOk(HTTPResponseStatus)
  81. /// The call was cancelled by the client.
  82. case cancelledByClient
  83. /// It was not possible to deserialize the response protobuf.
  84. case responseProtoDeserializationFailure
  85. /// It was not possible to serialize the request protobuf.
  86. case requestProtoSerializationFailure
  87. /// More than one response was received for a unary-response call.
  88. case responseCardinalityViolation
  89. /// The call deadline was exceeded.
  90. case deadlineExceeded(GRPCTimeout)
  91. }
  92. /// An error which should be thrown by either the client or server.
  93. public enum GRPCCommonError: Error, Equatable {
  94. /// An invalid state has been reached; something has gone very wrong.
  95. case invalidState(String)
  96. /// Compression was indicated in the "grpc-message-encoding" header but not in the gRPC message compression flag, or vice versa.
  97. case unexpectedCompression
  98. /// The given compression mechanism is not supported.
  99. case unsupportedCompressionMechanism(String)
  100. }
  101. extension GRPCServerError: GRPCStatusTransformable {
  102. public func asGRPCStatus() -> GRPCStatus {
  103. // These status codes are informed by: https://github.com/grpc/grpc/blob/master/doc/statuscodes.md
  104. switch self {
  105. case .unimplementedMethod(let method):
  106. return GRPCStatus(code: .unimplemented, message: "unknown method \(method)")
  107. case .base64DecodeError:
  108. return GRPCStatus(code: .internalError, message: "could not decode base64 message")
  109. case .requestProtoDeserializationFailure:
  110. return GRPCStatus(code: .internalError, message: "could not parse request proto")
  111. case .responseProtoSerializationFailure:
  112. return GRPCStatus(code: .internalError, message: "could not serialize response proto")
  113. case .requestCardinalityViolation:
  114. return GRPCStatus(code: .unimplemented, message: "request cardinality violation; method requires exactly one request but client sent more")
  115. case .serverNotWritable:
  116. return GRPCStatus.processingError
  117. }
  118. }
  119. }
  120. extension GRPCClientError: GRPCStatusTransformable {
  121. public func asGRPCStatus() -> GRPCStatus {
  122. switch self {
  123. case .HTTPStatusNotOk(let status):
  124. return GRPCStatus(code: .unknown, message: "server returned \(status.code) \(status.reasonPhrase)")
  125. case .cancelledByClient:
  126. return GRPCStatus(code: .cancelled, message: "client cancelled the call")
  127. case .responseCardinalityViolation:
  128. return GRPCStatus(code: .unimplemented, message: "response cardinality violation; method requires exactly one response but server sent more")
  129. case .responseProtoDeserializationFailure:
  130. return GRPCStatus(code: .internalError, message: "could not parse response proto")
  131. case .requestProtoSerializationFailure:
  132. return GRPCStatus(code: .internalError, message: "could not serialize request proto")
  133. case .deadlineExceeded(let timeout):
  134. return GRPCStatus(code: .deadlineExceeded, message: "call exceeded timeout of \(timeout)")
  135. }
  136. }
  137. }
  138. extension GRPCCommonError: GRPCStatusTransformable {
  139. public func asGRPCStatus() -> GRPCStatus {
  140. switch self {
  141. case .invalidState:
  142. return GRPCStatus.processingError
  143. case .unexpectedCompression:
  144. return GRPCStatus(code: .unimplemented, message: "compression was enabled for this gRPC message but not for this call")
  145. case .unsupportedCompressionMechanism(let mechanism):
  146. return GRPCStatus(code: .unimplemented, message: "unsupported compression mechanism \(mechanism)")
  147. }
  148. }
  149. }