Better logging for errors

This commit is contained in:
Christoph Hagen 2022-10-07 21:13:21 +02:00
parent 4490b2ca84
commit 7728ff7d35
2 changed files with 41 additions and 13 deletions

View File

@ -86,9 +86,14 @@ final class CapServer {
}
private func loadCaps() throws {
let data = try Data(contentsOf: dbFile)
caps = try JSONDecoder().decode([Cap].self, from: data)
.reduce(into: [:]) { $0[$1.id] = $1 }
do {
let data = try Data(contentsOf: dbFile)
caps = try JSONDecoder().decode([Cap].self, from: data)
.reduce(into: [:]) { $0[$1.id] = $1 }
} catch {
log("Failed to load caps: \(error)")
throw error
}
log("\(caps.count) caps loaded")
}
@ -146,10 +151,15 @@ final class CapServer {
// MARK: Counts
private func updateCounts() throws {
caps = try caps.mapValues {
var cap = $0
cap.count = try count(of: $0.id)
return cap
do {
caps = try caps.mapValues {
var cap = $0
cap.count = try count(of: $0.id)
return cap
}
} catch {
log("Failed to update counts: \(error)")
throw error
}
}

View File

@ -13,13 +13,9 @@ public func configure(_ app: Application) throws {
.appendingPathComponent("config.json")
let config: Config
if !FileManager.default.fileExists(atPath: configFile.path) {
config = .default
let configData = try JSONEncoder().encode(config)
try configData.write(to: configFile)
print("Wrote default configuration")
config = try writeDefaultCofig(to: configFile)
} else {
let configData = try Data(contentsOf: configFile)
config = try JSONDecoder().decode(Config.self, from: configData)
config = try loadConfig(at: configFile)
}
try Log.set(logFile: config.logPath)
@ -36,3 +32,25 @@ public func configure(_ app: Application) throws {
// Register routes to the router
try routes(app)
}
private func writeDefaultCofig(to path: URL) throws -> Config {
do {
let configData = try JSONEncoder().encode(Config.default)
try configData.write(to: path)
print("Wrote default configuration to \(path.path)")
return .default
} catch {
print("Failed to write default config file at \(path.path): \(error)")
throw error
}
}
private func loadConfig(at path: URL) throws -> Config {
do {
let configData = try Data(contentsOf: path)
return try JSONDecoder().decode(Config.self, from: configData)
} catch {
print("Failed to load config file at \(path.path): \(error)")
throw error
}
}