Skip to content

Commit

Permalink
add and replace missing key error
Browse files Browse the repository at this point in the history
Signed-off-by: wibe <[email protected]>
  • Loading branch information
wibed committed Mar 12, 2024
1 parent dedc546 commit 2fdc1f0
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 1 deletion.
6 changes: 6 additions & 0 deletions Sources/ImperialCore/Errors/SessionError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,28 @@ public enum SessionError: Error, CustomStringConvertible, AbortError {
/// Thrown when the user's access token is not found within the session's data
case usernotAuthenticated

/// Throws Errors when no object is stored in the session with the given key, or decoding fails.
case keynotFound(String)

public var description: String {
switch self {
case .usernotAuthenticated: return "User currently not authenticated"
case let .keynotFound(key): return "No element has been found with the key '\(key)'"
}
}

public var reason: String {
switch self {
case .usernotAuthenticated: return description
case .keynotFound: return description
}
}


public var status: HTTPStatus {
switch self {
case .usernotAuthenticated: return .unauthorized
case .keynotFound: return .internalServerError
}
}

Expand Down
3 changes: 2 additions & 1 deletion Sources/ImperialCore/Helpers/Sessions+Imperial.swift
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,10 @@ extension Session {
/// - Returns: The JSON from the session, decoded to the type passed in.
/// - Throws: Errors when no object is stored in the session with the given key, or decoding fails.
public func get<T>(_ key: String, as type: T.Type) throws -> T where T: Codable {
let keynotfoundError = SessionError.keynotFound(key)
guard let stored = data[key] else {
if _isOptional(T.self) { return Optional<Void>.none as! T }
throw Abort(.internalServerError, reason: "No element found in session with ket '\(key)'")
throw keynotfoundError
}
return try JSONDecoder().decode(T.self, from: Data(stored.utf8))
}
Expand Down

0 comments on commit 2fdc1f0

Please sign in to comment.