Encoding dictionaries in Perfect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// AppErrors.swift | |
// | |
// Created by Robert Bojor on 21/05/16. | |
// | |
import PerfectLib | |
public struct AppErrors { | |
enum ErrorTypes:String { | |
case SQLConnectionError | |
} | |
let errorData:[String:Dictionary<String, JSONValue>] = [ | |
"SQLConnectionError": ["code": "0" , "internalMessage": "SQL could not connect to the database", "userMessage": "Oops, something went wrong! Please try again later."], | |
] | |
func parseError(errorType: ErrorTypes) -> String { | |
var errorPayloadString:String = "" | |
let encoder = JSONEncoder() | |
let preErrorPayloadObject:Dictionary<String, JSONValue> = errorData[errorType.rawValue]! | |
print("preErrorPayloadObject: \(preErrorPayloadObject)") | |
let errorPayloadObject:Dictionary<String, JSONValue> = ["error": preErrorPayloadObject] | |
print("errorPayloadObject: \(errorPayloadObject)") | |
// Encode the error | |
do { | |
errorPayloadString = try encoder.encode(errorPayloadObject) | |
print("Encoded error to: \(errorPayloadString)") | |
} catch { | |
errorPayloadString = "" | |
print("Failed to encode") | |
} | |
return errorPayloadString | |
} | |
} | |
// Calling it from anywhere else in the project and getting the string ready to append to the body | |
// let jsonString = AppErrors().parseError(AppErrors.ErrorTypes.SQLConnectionError) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment