diff --git a/LeStorage/Services.swift b/LeStorage/Services.swift index cadada8..a987f7f 100644 --- a/LeStorage/Services.swift +++ b/LeStorage/Services.swift @@ -116,6 +116,8 @@ public class Services { if let apiCallId, let type = (T.self as? any Storable.Type) { try Store.main.rescheduleApiCall(id: apiCallId, type: type) Store.main.logFailedAPICall(apiCallId, collectionName: type.resourceName(), error: errorString) + } else { + Store.main.logFailedAPICall(request: request, error: errorString) } throw ServiceError.responseError(response: errorString) @@ -357,10 +359,14 @@ public class Services { fileprivate func errorMessageFromResponse(data: Data) -> String? { do { if let jsonObject = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] { - if let stringsArray = jsonObject.values.first as? [String] { - return stringsArray.first - } else if let string = jsonObject.values.first as? String { - return string + if let tuple = jsonObject.first { + var error = "" + if let stringsArray = tuple.value as? [String], let first = stringsArray.first { + error = first + } else if let string = tuple.value as? String { + error = string + } + return "\(error) (\(tuple.key))" } } } catch { diff --git a/LeStorage/Store.swift b/LeStorage/Store.swift index 895c1db..325f3ed 100644 --- a/LeStorage/Store.swift +++ b/LeStorage/Store.swift @@ -282,11 +282,12 @@ public class Store { guard let failedAPICallsCollection = self._failedAPICallsCollection, let collection = self._collections[collectionName], + collectionName != FailedAPICall.resourceName(), let apiCall = try? collection.apiCallById(apiCallId) else { return } - if !failedAPICallsCollection.contains(where: { $0.callId == apiCallId }) && apiCall.attemptsCount > 5 { + if !failedAPICallsCollection.contains(where: { $0.callId == apiCallId }) && apiCall.attemptsCount > 6 { do { let string = try apiCall.jsonString() @@ -299,4 +300,22 @@ public class Store { } + func logFailedAPICall(request: URLRequest, error: String) { + + guard let failedAPICallsCollection = self._failedAPICallsCollection, + let body: Data = request.httpBody, + let bodyString = String(data: body, encoding: .utf8), + let url = request.url?.absoluteString else { + return + } + + do { + let failedAPICall = FailedAPICall(callId: request.hashValue.formatted(), type: url, apiCall: bodyString, error: error) + try failedAPICallsCollection.addOrUpdate(instance: failedAPICall) + } catch { + Logger.error(error) + } + + } + }