@@ -25,11 +25,15 @@ struct ContentView: View {
25
25
VStack ( alignment: . leading, spacing: 20 ) {
26
26
TextField ( " Username " , text: $name)
27
27
SecureField ( " Password " , text: $password)
28
- let buttonDisabled = name. isEmpty || password. isEmpty
28
+ let inputIncomplete = name. isEmpty || password. isEmpty
29
29
Button {
30
30
Task {
31
31
isLoading = true
32
- response = await self . register ( )
32
+ do {
33
+ response = try await self . register ( )
34
+ } catch {
35
+ response = error. localizedDescription
36
+ }
33
37
isLoading = false
34
38
}
35
39
} label: {
@@ -45,13 +49,13 @@ struct ContentView: View {
45
49
}
46
50
}
47
51
}
48
- . disabled ( buttonDisabled || isLoading)
49
- . opacity ( buttonDisabled ? 0.5 : 1 )
52
+ . disabled ( inputIncomplete || isLoading)
53
+ . opacity ( inputIncomplete ? 0.5 : 1 )
50
54
Text ( response)
51
55
} . padding ( 100 )
52
56
}
53
57
54
- func register( ) async -> String {
58
+ func register( ) async throws -> String {
55
59
guard let url = URL ( string: " http://127.0.0.1:7000/invoke " ) else {
56
60
fatalError ( " invalid url " )
57
61
}
@@ -63,21 +67,17 @@ struct ContentView: View {
63
67
}
64
68
request. httpBody = jsonRequest
65
69
66
- do {
67
- let ( data, response) = try await URLSession . shared. data ( for: request)
70
+ let ( data, response) = try await URLSession . shared. data ( for: request)
68
71
69
- guard let httpResponse = response as? HTTPURLResponse else {
70
- return " invalid response, expected HTTPURLResponse "
71
- }
72
- guard httpResponse. statusCode == 200 else {
73
- return " invalid response code: \( httpResponse. statusCode) "
74
- }
75
-
76
- let jsonResponse = try JSONDecoder ( ) . decode ( Response . self, from: data)
77
- return jsonResponse. message
78
- } catch {
79
- return error. localizedDescription
72
+ guard let httpResponse = response as? HTTPURLResponse else {
73
+ throw CommunicationError ( reason: " Invalid response, expected HTTPURLResponse. " )
74
+ }
75
+ guard httpResponse. statusCode == 200 else {
76
+ throw CommunicationError ( reason: " Invalid response code: \( httpResponse. statusCode) " )
80
77
}
78
+
79
+ let jsonResponse = try JSONDecoder ( ) . decode ( Response . self, from: data)
80
+ return jsonResponse. message
81
81
}
82
82
}
83
83
@@ -86,3 +86,10 @@ struct ContentView_Previews: PreviewProvider {
86
86
ContentView ( )
87
87
}
88
88
}
89
+
90
+ struct CommunicationError : LocalizedError {
91
+ let reason : String
92
+ var errorDescription : String ? {
93
+ self . reason
94
+ }
95
+ }
0 commit comments