Skip to content
This repository was archived by the owner on Sep 6, 2025. It is now read-only.
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 53 additions & 5 deletions Sources/DFService/ServiceError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,64 @@
///
/// - api: Indicates an API error with an associated error code and message.
/// - notImplemented: Indicates that a feature or method is not yet implemented. The default value includes the file and function name.

import Foundation

public enum ServiceError: Error {
/// API 错误,包含错误代码和消息
/// - Parameters:
/// - code: 错误代码
/// - message: 错误消息
/// - debugMessage: 可选的调试消息,默认为 nil
/// - Example: `ServiceError.api(code: 404, message: "Not Found")`
/// - Example: `ServiceError.api(code: 500, message: "Internal Server Error", debugMessage: "Database connection failed")`
case api(code: Int, message: String, debugMessage: String? = nil)
/// - detail: 可选的调试消息,默认为 nil
case api(code: Int, message: String, detail: String? = nil)

/// 未实现
case notImplemented(String = #fileID + " " + #function)
case notImplemented(String = #function)
/// 自定义错误
case custom(Error)

public static func from(_ error: Error) -> ServiceError {
if let serviceError = error as? ServiceError {
return serviceError
} else {
return .custom(error)
}
}
}

/// 扩展 ServiceError 以提供错误描述
extension ServiceError: CustomStringConvertible, CustomDebugStringConvertible {
public var errorCode: Int {
switch self {
case .api(let code, _, _):
return code
case .notImplemented:
return 0 // 未实现的错误没有特定的错误代码
case .custom(let error):
return (error as NSError).code // 使用 NSError 的代码
}
}
public var description: String {
switch self {
case .api(_, let message, _):
return message
case .notImplemented(let location):
return "未实现: \(location)"
case .custom(let error):
return error.localizedDescription
}
}

public var debugDescription: String {

switch self {
case .api(let code, let message, let detail):
return
"ServiceError api - Code: \(code), Message: \(message), Detail: \(detail ?? "No detail")"
case .notImplemented(let location):
return "ServiceError - Location: \(location)"
case .custom(let error):
return "ServiceError - \(error.localizedDescription)"
}
}
}