Skip to content

Commit c49f03d

Browse files
authored
Merge pull request #10 from grahamburgsma/fcm-error
Added FCMError
2 parents a5b4e08 + 4827a78 commit c49f03d

File tree

2 files changed

+54
-8
lines changed

2 files changed

+54
-8
lines changed

Sources/FCM/FCMError.swift

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
public struct GoogleError: Error, Decodable {
2+
public let code: Int
3+
public let message: String
4+
public let status: String
5+
public let fcmError: FCMError?
6+
7+
private enum TopLevelCodingKeys: String, CodingKey {
8+
case error
9+
}
10+
11+
private enum CodingKeys: String, CodingKey {
12+
case code, message, status, details
13+
}
14+
15+
public init(from decoder: Decoder) throws {
16+
let container = try decoder.container(keyedBy: TopLevelCodingKeys.self)
17+
.nestedContainer(keyedBy: CodingKeys.self, forKey: .error)
18+
19+
code = try container.decode(Int.self, forKey: .code)
20+
message = try container.decode(String.self, forKey: .message)
21+
status = try container.decode(String.self, forKey: .status)
22+
23+
var details = try container.nestedUnkeyedContainer(forKey: .details)
24+
fcmError = try? details.decode(FCMError.self)
25+
}
26+
}
27+
28+
public struct FCMError: Error, Decodable {
29+
public let errorCode: ErrorCode
30+
31+
public enum ErrorCode: String, Decodable {
32+
case unspecified = "UNSPECIFIED_ERROR"
33+
case invalid = "INVALID_ARGUMENT"
34+
case unregistered = "UNREGISTERED"
35+
case senderIDMismatch = "SENDER_ID_MISMATCH"
36+
case quotaExceeded = "QUOTA_EXCEEDED"
37+
case apnsAuth = "APNS_AUTH_ERROR"
38+
case unavailable = "UNAVAILABLE"
39+
case `internal` = "INTERNAL"
40+
}
41+
}

Sources/FCM/Helpers/FCM+SendMessage.swift

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -28,18 +28,23 @@ extension FCM {
2828
let payload = Payload(validate_only: false, message: message)
2929
try req.content.encode(payload, as: .json)
3030
}.map { res in
31-
struct Result: Codable {
32-
var name: String
33-
}
3431
guard let data = res.http.body.data else {
3532
throw Abort(.notFound, reason: "Data not found")
3633
}
37-
do {
38-
let result = try JSONDecoder().decode(Result.self, from: data)
39-
return result.name
40-
} catch {
41-
throw Abort(.internalServerError, reason: String(data: data, encoding: .utf8) ?? "Unable to decode Firebase response")
34+
35+
guard 200 ..< 300 ~= res.http.status.code else {
36+
if let googleError = try? res.content.syncDecode(GoogleError.self) {
37+
throw googleError
38+
} else {
39+
let reason = String(data: data, encoding: .utf8) ?? "Unable to decode Firebase response"
40+
throw Abort(.internalServerError, reason: reason)
41+
}
42+
}
43+
44+
struct Result: Codable {
45+
var name: String
4246
}
47+
return try res.content.syncDecode(Result.self).name
4348
}
4449
}
4550
}

0 commit comments

Comments
 (0)