Skip to content

Commit 2dfd6ae

Browse files
committed
rework error struct
Fixes: NIO-7
1 parent 6a7c080 commit 2dfd6ae

File tree

12 files changed

+170
-20
lines changed

12 files changed

+170
-20
lines changed

Sources/MatrixClient/API/AccountData.swift

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ public struct MatrixGetAccountData<T: MatrixAccountData>: MatrixResponse, Matrix
3030
with parameters: RequestParameter) throws -> URLComponents
3131
{
3232
guard let fqmxid = parameters.userID.FQMXID else {
33-
throw MatrixError.NotFound
33+
throw MatrixErrorCode.NotFound
3434
}
3535

3636
if let roomID = parameters.roomID {
@@ -66,7 +66,7 @@ public struct MatrixSetAccountData<T: MatrixAccountData>: MatrixRequest {
6666
with parameters: MatrixGetAccountData<T>.RequestParameter) throws -> URLComponents
6767
{
6868
guard let fqmxid = parameters.userID.FQMXID else {
69-
throw MatrixError.NotFound
69+
throw MatrixErrorCode.NotFound
7070
}
7171

7272
if let roomID = parameters.roomID {
@@ -90,7 +90,7 @@ public extension MatrixAccountData {
9090

9191
func components(for homeserver: MatrixHomeserver, with userID: MatrixUserIdentifier) throws -> URLComponents {
9292
guard let fqmxid = userID.FQMXID else {
93-
throw MatrixError.NotFound
93+
throw MatrixErrorCode.NotFound
9494
}
9595
return homeserver.path("/_matrix/client/v3/user/\(fqmxid)/account_data/\(Self.type)")
9696
}

Sources/MatrixClient/API/Auth/Interactive.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ public struct MatrixInteractiveAuth: MatrixResponse {
1515
session: String? = nil,
1616
completed: [MatrixLoginFlow]? = nil,
1717
error: String? = nil,
18-
errcode: MatrixError? = nil
18+
errcode: MatrixErrorCode? = nil
1919
) {
2020
self.flows = flows
2121
self.params = params
@@ -39,7 +39,7 @@ public struct MatrixInteractiveAuth: MatrixResponse {
3939
public var completed: [MatrixLoginFlow]?
4040

4141
public var error: String?
42-
public var errcode: MatrixError?
42+
public var errcode: MatrixErrorCode?
4343

4444
// MARK: Dynamic vars
4545

Sources/MatrixClient/API/Filter.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ extension MatrixFilterRequest: MatrixRequest {
3434
let userId = parameters.user,
3535
let filterId = parameters.filter
3636
else {
37-
throw MatrixError.Unrecognized
37+
throw MatrixErrorCode.Unrecognized
3838
}
3939

4040
var components = homeserver.url

Sources/MatrixClient/API/HomeServer.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ public struct MatrixHomeserver: Codable {
3737
@available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
3838
public init(resolve string: String, withUrlSession urlSession: URLSession = URLSession.shared) async throws {
3939
guard let self = MatrixHomeserver(string: string) else {
40-
throw MatrixError.NotFound
40+
throw MatrixErrorCode.NotFound
4141
}
4242

4343
var res: MatrixWellKnown

Sources/MatrixClient/API/Request.swift

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ public extension MatrixRequest {
5252

5353
if Self.requiresAuth {
5454
guard let token = token else {
55-
throw MatrixError.Forbidden
55+
throw MatrixErrorCode.Forbidden
5656
}
5757
urlRequest.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
5858
}
@@ -101,7 +101,7 @@ public extension MatrixRequest {
101101
let (data, urlResponse) = try await urlSession.data(for: request)
102102

103103
guard let response = urlResponse as? HTTPURLResponse else {
104-
throw MatrixError.Unknown
104+
throw MatrixErrorCode.Unknown
105105
}
106106

107107
return (data, response)
@@ -140,7 +140,7 @@ public extension MatrixRequest {
140140
guard let response = response as? HTTPURLResponse,
141141
let data = data
142142
else {
143-
callback(.failure(MatrixError.Unknown))
143+
callback(.failure(MatrixErrorCode.Unknown))
144144
return
145145
}
146146

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
//
2+
// WhoAmI.swift
3+
//
4+
//
5+
// Created by Finn Behrens on 23.04.22.
6+
//
7+
8+
import Foundation
9+
10+
public struct MatrixWhoAmIRequest: MatrixRequest {
11+
public func components(for homeserver: MatrixHomeserver, with parameters: ()) throws -> URLComponents {
12+
homeserver.path("/_matrix/client/v3/account/whoami")
13+
}
14+
15+
public static var httpMethod: HttpMethod {
16+
.GET
17+
}
18+
19+
public static var requiresAuth: Bool {
20+
true
21+
}
22+
23+
public typealias Response = MatrixWhoAmI
24+
25+
public typealias URLParameters = ()
26+
}
27+
28+
public struct MatrixWhoAmI: MatrixResponse {
29+
/// Device ID associated with the access token.
30+
///
31+
/// If no device is associated with the access token (such as in the case of application services) then this field can be omitted. Otherwise this is required.
32+
public var deviceID: String?
33+
34+
/// When true, the user is a Guest User.
35+
///
36+
/// When not present or false, the user is presumed to be a non-guest user.
37+
public var isGuest: Bool? = false
38+
39+
/// The user ID that owns the access token.
40+
public var userID: MatrixFullUserIdentifier
41+
42+
enum CodingKeys: String, CodingKey {
43+
case deviceID = "device_id"
44+
case isGuest = "is_guest"
45+
case userID = "user_id"
46+
}
47+
}

Sources/MatrixClient/Error.swift

Lines changed: 98 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
import Foundation
99

10-
public enum MatrixError: String, Error, Codable {
10+
public enum MatrixCommonErrorCode: String, Error, Codable {
1111
case Forbidden = "M_FORBIDDEN"
1212
case Unknown = "M_UNKNOWN"
1313
case UnknownToken = "M_UNKNOWN_TOKEN"
@@ -42,9 +42,86 @@ public enum MatrixError: String, Error, Codable {
4242
case InvalidParam = "M_INVALID_PARAM"
4343
}
4444

45+
public struct MatrixErrorCode: RawRepresentable, Error, Codable {
46+
var common: MatrixCommonErrorCode?
47+
var string: String?
48+
49+
public var rawValue: String {
50+
if let common = common {
51+
return common.rawValue
52+
}
53+
return string!
54+
}
55+
56+
public init?(rawValue: String) {
57+
self.common = MatrixCommonErrorCode(rawValue: rawValue)
58+
if common == nil {
59+
self.string = rawValue
60+
}
61+
}
62+
63+
public init(_ common: MatrixCommonErrorCode) {
64+
self.common = common
65+
}
66+
}
67+
68+
extension MatrixErrorCode {
69+
public init(from decoder: Decoder) throws {
70+
let container = try decoder.singleValueContainer()
71+
let rawValue = try container.decode(String.self)
72+
self.init(rawValue: rawValue)!
73+
}
74+
75+
public func encode(to encoder: Encoder) throws {
76+
var container = encoder.singleValueContainer()
77+
try container.encode(self.rawValue)
78+
}
79+
}
80+
81+
extension MatrixErrorCode: ExpressibleByStringLiteral {
82+
public init(stringLiteral value: StringLiteralType) {
83+
self.init(rawValue: value)!
84+
}
85+
}
86+
87+
public extension MatrixErrorCode {
88+
static let Forbidden = MatrixErrorCode(.Forbidden)
89+
static let Unknown = MatrixErrorCode(.Unknown)
90+
static let UnknownToken = MatrixErrorCode(.UnknownToken)
91+
static let BadJSON = MatrixErrorCode(.BadJSON)
92+
static let NotFound = MatrixErrorCode(.NotFound)
93+
static let LimitExceeded = MatrixErrorCode(.LimitExceeded)
94+
static let UserInUse = MatrixErrorCode(.UserInUse)
95+
static let RoomInUse = MatrixErrorCode(.RoomInUse)
96+
static let BadPagination = MatrixErrorCode(.BadPagination)
97+
static let Unauthorized = MatrixErrorCode(.Unauthorized)
98+
static let OldVersion = MatrixErrorCode(.OldVersion)
99+
static let Unrecognized = MatrixErrorCode(.Unrecognized)
100+
static let LoginEmailURLNotYet = MatrixErrorCode(.LoginEmailURLNotYet)
101+
static let ThreePIDAuthFailed = MatrixErrorCode(.ThreePIDAuthFailed)
102+
static let ThreePIDInUse = MatrixErrorCode(.ThreePIDInUse)
103+
static let ThreePIDNotFound = MatrixErrorCode(.ThreePIDNotFound)
104+
static let ServerNotTrusted = MatrixErrorCode(.ServerNotTrusted)
105+
static let GuestAccessForbidden = MatrixErrorCode(.GuestAccessForbidden)
106+
static let ConsentNotGiven = MatrixErrorCode(.ConsentNotGiven)
107+
static let ResourceLimitExceeded = MatrixErrorCode(.ResourceLimitExceeded)
108+
static let BackupWrongKeysVersion = MatrixErrorCode(.BackupWrongKeysVersion)
109+
static let PasswordTooShort = MatrixErrorCode(.PasswordTooShort)
110+
static let PasswordNoDigit = MatrixErrorCode(.PasswordNoDigit)
111+
static let PasswordNoUppercase = MatrixErrorCode(.PasswordNoUppercase)
112+
static let PasswordNoLowercase = MatrixErrorCode(.PasswordNoLowercase)
113+
static let PasswordNoSymbol = MatrixErrorCode(.PasswordNoSymbol)
114+
static let PasswordInDictionary = MatrixErrorCode(.PasswordInDictionary)
115+
static let PasswordWeak = MatrixErrorCode(.PasswordWeak)
116+
static let TermsNotSigned = MatrixErrorCode(.TermsNotSigned)
117+
static let InvalidPepper = MatrixErrorCode(.InvalidPepper)
118+
static let Exclusive = MatrixErrorCode(.Exclusive)
119+
static let InvalidParam = MatrixErrorCode(.InvalidParam)
120+
}
121+
45122
public struct MatrixServerError: Error, Codable {
46123
/// Error code
47-
public var errcode: MatrixError
124+
public var errcode: MatrixErrorCode
48125

49126
/// Error message reported by the server
50127
public var error: String
@@ -57,7 +134,25 @@ public struct MatrixServerError: Error, Codable {
57134
public init(json: Data, code: Int? = nil) throws {
58135
let decoder = JSONDecoder()
59136

60-
self = try decoder.decode(Self.self, from: json)
137+
do {
138+
self = try decoder.decode(Self.self, from: json)
139+
} catch {
140+
throw MatrixInvalidError(data: json, code: code)
141+
}
61142
self.code = code
62143
}
63144
}
145+
146+
public struct MatrixInvalidError: Error, LocalizedError {
147+
public var data: Data
148+
public var code: Int?
149+
150+
public init(data: Data, code: Int? = nil) {
151+
self.data = data
152+
self.code = code
153+
}
154+
155+
var localisedDescription: String {
156+
NSLocalizedString("Failed to parse error result for code \(code ?? -1)", comment: "MatrixInvalidError")
157+
}
158+
}

Sources/MatrixClient/MatrixClient.swift

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,14 @@ public struct MatrixClient {
145145
.response(on: homeserver, withToken: accessToken, with: (), withUrlSession: urlSession, callback: callback)
146146
}
147147

148+
149+
@available(swift, introduced: 5.5)
150+
@available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
151+
public func whoami() async throws -> MatrixWhoAmI {
152+
return try await MatrixWhoAmIRequest()
153+
.response(on: homeserver, withToken: accessToken, with: (), withUrlSession: urlSession)
154+
}
155+
148156
@available(swift, introduced: 5.5)
149157
@available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
150158
public func sync(parameters: MatrixSyncRequest.Parameters) async throws -> MatrixSync {
@@ -172,7 +180,7 @@ public struct MatrixClient {
172180
public func isReady() async throws {
173181
let versions = try await getVersions()
174182
if !versions.versions.contains("v1.2") {
175-
throw MatrixError.NotFound
183+
throw MatrixErrorCode.NotFound
176184
}
177185
}
178186
}

Sources/MatrixClient/MatrixClient/MatrixClient+AccountData.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ public extension MatrixClient {
1212
@available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
1313
func getDisplayName(_ userID: MatrixUserIdentifier) async throws -> String {
1414
guard let userID = userID.FQMXID else {
15-
throw MatrixError.NotFound
15+
throw MatrixErrorCode.NotFound
1616
}
1717
return try await getDisplayName(userID: userID)
1818
}
@@ -29,7 +29,7 @@ public extension MatrixClient {
2929
@available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
3030
func setDisplayName(_ displayName: String, _ userID: MatrixUserIdentifier) async throws {
3131
guard let userID = userID.FQMXID else {
32-
throw MatrixError.NotFound
32+
throw MatrixErrorCode.NotFound
3333
}
3434

3535
try await setDisplayName(displayName, userID: userID)

Sources/MatrixClient/MatrixClient/MatrixClient+Auth.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ public extension MatrixClient {
4444
case let .interactive(flows):
4545
return flows
4646
default:
47-
throw MatrixError.NotFound
47+
throw MatrixErrorCode.NotFound
4848
}
4949
}
5050

0 commit comments

Comments
 (0)