@@ -80,6 +80,10 @@ public class API {
80
80
return internalDefaultURLSession
81
81
}
82
82
83
+ public class var acceptableStatusCodes : [ Int ] {
84
+ return [ Int] ( 200 ..< 300 )
85
+ }
86
+
83
87
// build NSURLRequest
84
88
public class func URLRequest( method: Method , _ path: String , _ parameters: [ String : AnyObject ] = [ : ] ) -> NSURLRequest ? {
85
89
if let components = NSURLComponents ( URL: baseURL ( ) , resolvingAgainstBaseURL: true ) {
@@ -135,10 +139,15 @@ public class API {
135
139
}
136
140
137
141
let statusCode = ( URLResponse as? NSHTTPURLResponse ) ? . statusCode ?? 0
138
- if !contains( 200 ..< 300 , statusCode) {
139
- let userInfo = [ NSLocalizedDescriptionKey: " received status code that represents error " ]
140
- let error = NSError ( domain: APIKitErrorDomain, code: statusCode, userInfo: userInfo)
141
- dispatch_async ( mainQueue, { handler ( . Failure( Box ( error) ) ) } )
142
+ if !contains( self . acceptableStatusCodes, statusCode) {
143
+ let error : NSError = {
144
+ switch self . responseBodyParser ( ) . parseData ( data) {
145
+ case . Success( let box) : return self . responseErrorFromObject ( box. unbox)
146
+ case . Failure( let box) : return box. unbox
147
+ }
148
+ } ( )
149
+
150
+ dispatch_async ( mainQueue) { handler ( failure ( error) ) }
142
151
return
143
152
}
144
153
@@ -150,8 +159,8 @@ public class API {
150
159
let error = NSError ( domain: APIKitErrorDomain, code: 0 , userInfo: userInfo)
151
160
return failure ( error)
152
161
}
153
-
154
162
}
163
+
155
164
dispatch_async ( mainQueue, { handler ( mappedResponse) } )
156
165
}
157
166
@@ -166,6 +175,12 @@ public class API {
166
175
return nil
167
176
}
168
177
}
178
+
179
+ public class func responseErrorFromObject( object: AnyObject ) -> NSError {
180
+ let userInfo = [ NSLocalizedDescriptionKey: " received status code that represents error " ]
181
+ let error = NSError ( domain: APIKitErrorDomain, code: 0 , userInfo: userInfo)
182
+ return error
183
+ }
169
184
}
170
185
171
186
public class URLSessionDelegate : NSObject , NSURLSessionDelegate , NSURLSessionDataDelegate {
0 commit comments