Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Encoding dictionaries in Perfect
// 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