Improves user error message

multistore
Laurent 1 year ago
parent 399e43d03a
commit 7c640d5157
  1. 25
      LeStorage/Services.swift

@ -110,19 +110,21 @@ public class Services {
{"detail":"Informations d'authentification non fournies."} {"detail":"Informations d'authentification non fournies."}
*/ */
Logger.log("Failed Run \(request.httpMethod ?? "") \(request.url?.absoluteString ?? "")") Logger.log("Failed Run \(request.httpMethod ?? "") \(request.url?.absoluteString ?? "")")
var errorString: String = String(data: task.0, encoding: .utf8) ?? "" let errorString: String = String(data: task.0, encoding: .utf8) ?? ""
var errorMessage = ErrorMessage(error: errorString, domain: "")
if let message = self.errorMessageFromResponse(data: task.0) { if let message = self.errorMessageFromResponse(data: task.0) {
errorString = message errorMessage = message
} }
if let apiCallId, let type = (T.self as? any Storable.Type) { if let apiCallId, let type = (T.self as? any Storable.Type) {
try Store.main.rescheduleApiCalls(id: apiCallId, type: type) try Store.main.rescheduleApiCalls(id: apiCallId, type: type)
Store.main.logFailedAPICall(apiCallId, request: request, collectionName: type.resourceName(), error: errorString) Store.main.logFailedAPICall(apiCallId, request: request, collectionName: type.resourceName(), error: errorMessage.message)
} else { } else {
Store.main.logFailedAPICall(request: request, error: errorString) Store.main.logFailedAPICall(request: request, error: errorMessage.message)
} }
throw ServiceError.responseError(response: errorString) throw ServiceError.responseError(response: errorMessage.error)
} }
} }
return try jsonDecoder.decode(T.self, from: task.0) return try jsonDecoder.decode(T.self, from: task.0)
@ -358,7 +360,7 @@ public class Services {
/// Parse a json data and tries to extract its error message /// Parse a json data and tries to extract its error message
/// - Parameters: /// - Parameters:
/// - data: some JSON data /// - data: some JSON data
fileprivate func errorMessageFromResponse(data: Data) -> String? { fileprivate func errorMessageFromResponse(data: Data) -> ErrorMessage? {
do { do {
if let jsonObject = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] { if let jsonObject = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
if let tuple = jsonObject.first { if let tuple = jsonObject.first {
@ -368,7 +370,7 @@ public class Services {
} else if let string = tuple.value as? String { } else if let string = tuple.value as? String {
error = string error = string
} }
return "\(error) (\(tuple.key))" return ErrorMessage(error: error, domain: tuple.key)
} }
} }
} catch { } catch {
@ -379,6 +381,15 @@ public class Services {
} }
struct ErrorMessage {
let error: String
let domain: String
var message: String {
return "\(self.error) (\(self.domain))"
}
}
struct AuthResponse: Codable { struct AuthResponse: Codable {
let token: String let token: String
} }

Loading…
Cancel
Save