Something went wrong. Try again.
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677import Hummingbirdimport HTTPTypesimport NIOCore
/// An error the API answers with a JSON body of the form/// `{"error": "<code>", "message": "<text>"}`, which is what the Go service/// sent and what EffemKit parses.struct AppError: Error, HTTPResponseError, Sendable { let status: HTTPResponse.Status let code: String let message: String? var headers: HTTPFields = [:]
init(_ status: HTTPResponse.Status, code: String, message: String? = nil, headers: HTTPFields = [:]) { self.status = status self.code = code self.message = message self.headers = headers }
static func invalidRequest(_ message: String) -> AppError { AppError(.badRequest, code: "InvalidRequest", message: message) }
static func notFound(_ message: String) -> AppError { AppError(.notFound, code: "NotFound", message: message) }
static func authRequired(_ message: String = "authentication required") -> AppError { AppError(.unauthorized, code: "AuthRequired", message: message) }
static func forbidden(_ message: String = "missing required scope") -> AppError { AppError(.forbidden, code: "Forbidden", message: message) }
static func upstream(_ message: String = "podcast index request failed") -> AppError { AppError(.badGateway, code: "UpstreamError", message: message) }
static let internalError = AppError(.internalServerError, code: "InternalError")
func response(from request: Request, context: some RequestContext) throws -> Response { var fields = headers fields[.contentType] = "application/json; charset=utf-8" var body = "{\"error\":\(JSONString.quoted(code))" if let message { body += ",\"message\":\(JSONString.quoted(message))" } body += "}" return Response(status: status, headers: fields, body: .init(byteBuffer: ByteBuffer(string: body))) }}
enum JSONString { /// Quotes a string for direct use inside hand-built JSON. static func quoted(_ value: String) -> String { var out = "\"" for scalar in value.unicodeScalars { switch scalar { case "\"": out += "\\\"" case "\\": out += "\\\\" case "\n": out += "\\n" case "\r": out += "\\r" case "\t": out += "\\t" default: if scalar.value < 0x20 { out += String(format: "\\u%04x", scalar.value) } else { out.unicodeScalars.append(scalar) } } } return out + "\"" }}