106 lines
3.1 KiB
Swift
106 lines
3.1 KiB
Swift
import CSDL2
|
|
|
|
public struct SDLError: Error {
|
|
|
|
public let errorMessage: String
|
|
|
|
internal let debugInformation: DebugInformation?
|
|
}
|
|
|
|
extension SDLError: CustomStringConvertible {
|
|
|
|
public var description: String {
|
|
|
|
return errorMessage
|
|
}
|
|
}
|
|
|
|
extension SDLError: CustomDebugStringConvertible {
|
|
public var debugDescription: String {
|
|
|
|
var description = errorMessage
|
|
if let debugInformation = debugInformation {
|
|
description += " " + "(\(debugInformation.description))"
|
|
}
|
|
return description
|
|
}
|
|
}
|
|
|
|
internal extension SDLError {
|
|
|
|
final class DebugInformation: CustomStringConvertible, Sendable {
|
|
|
|
public let file: String
|
|
|
|
public let type: String
|
|
|
|
public let function: String
|
|
|
|
public let line: UInt
|
|
|
|
internal init(file: String,
|
|
type: Any,
|
|
function: String,
|
|
line: UInt) {
|
|
|
|
self.file = file
|
|
self.function = function
|
|
self.line = line
|
|
self.type = String(reflecting: type)
|
|
}
|
|
|
|
public var description: String {
|
|
let fileName = file.split(separator: "/").last.flatMap { String($0) } ?? file
|
|
return "\(fileName):\(line.description) \(type).\(function)"
|
|
}
|
|
}
|
|
}
|
|
|
|
internal extension SDLError {
|
|
static func current(debugInformation: DebugInformation? = nil) -> SDLError? {
|
|
|
|
guard let cString = SDL_GetError()
|
|
else { return nil }
|
|
|
|
SDL_ClearError()
|
|
let errorDescription = String(cString: cString)
|
|
|
|
return SDLError(errorMessage: errorDescription, debugInformation: debugInformation)
|
|
}
|
|
}
|
|
|
|
internal extension Int32 {
|
|
func sdlThrow(file: String = #file,
|
|
type: Any,
|
|
function: String = #function,
|
|
line: UInt = #line) throws(SDLError) {
|
|
|
|
guard self >= 0 else {
|
|
let debugInformation = SDLError.DebugInformation(file: file, type: type, function: function, line: line)
|
|
guard let error = SDLError.current(debugInformation: debugInformation) else {
|
|
assertionFailure("No error for error code \(self)")
|
|
throw SDLError(errorMessage: "Error code \(self)", debugInformation: debugInformation)
|
|
}
|
|
throw error
|
|
}
|
|
}
|
|
}
|
|
|
|
internal extension Optional {
|
|
func sdlThrow(file: String = #file,
|
|
type: Any,
|
|
function: String = #function,
|
|
line: UInt = #line) throws(SDLError) -> Wrapped {
|
|
|
|
guard let value = self else {
|
|
let debugInformation = SDLError.DebugInformation(file: file, type: type, function: function, line: line)
|
|
guard let error = SDLError.current(debugInformation: debugInformation) else {
|
|
assertionFailure("No error for nil value \(Wrapped.self)")
|
|
throw SDLError(errorMessage: "Nil value \(Wrapped.self)", debugInformation: debugInformation)
|
|
}
|
|
throw error
|
|
}
|
|
return value
|
|
}
|
|
}
|