Skip to content

Commit

Permalink
More flexible error handling at request level.
Browse files Browse the repository at this point in the history
  • Loading branch information
bteapot committed May 19, 2022
1 parent 6910f53 commit e445385
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 26 deletions.
10 changes: 6 additions & 4 deletions Sources/Server/Server.swift
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ open class Server {
.take(until: self.assets.signal.map(value: ()))
}

public typealias Catcher<R> = (Error) throws -> R

/// Perfom network request.
///
/// - Parameters:
Expand All @@ -85,7 +87,7 @@ open class Server {
query: [String: String] = [:],
send: Send = .void(),
take: Take<R>,
catch: Config.Catcher? = nil
catcher: Catcher<R>? = nil
) -> SignalProducer<R, Error> {
let (config, session) = self.assets.value

Expand Down Expand Up @@ -145,9 +147,9 @@ open class Server {
}
.flatMapError { error in
Tools.mapError(
config: config,
catch: `catch`,
error: error
config: config,
catcher: catcher,
error: error
)
}
.take(until: self.assets.signal.map(value: ()))
Expand Down
48 changes: 26 additions & 22 deletions Sources/Server/Tools.swift
Original file line number Diff line number Diff line change
Expand Up @@ -179,32 +179,36 @@ extension Server {
// MARK: - Map or skip errors

public static func mapError<R>(
config: Config,
catch: Config.Catcher?,
error: Error
config: Config,
catcher: Catcher<R>?,
error: Error
) -> SignalProducer<R, Error> {
SignalProducer { observer, lifetime in
// error mapping defined by request or config?
if let catcher = `catch` ?? config.catcher {
// map error or terminate signal
if let mapped = catcher(error) {
observer.send(error: mapped)
} else {
observer.sendCompleted()
}
// error handling defined by request?
if let catcher = catcher {
// map error or send value and terminate
return .init { try catcher(error) }
}

// error mapping defined by config?
if let catcher = config.catcher {
// map error or terminate signal
if let mapped = catcher(error) {
return .init(error: mapped)
} else {
// standard error handling
switch error {
case URLError.cancelled:
// request cancelled, will complete without values or errors
observer.sendCompleted()

default:
// send error
observer.send(error: error)
}
return .empty
}
}

// standard error handling
switch error {
case URLError.cancelled:
// request cancelled, will complete without values or errors
return .empty

default:
// send original error
return .init(error: error)
}
}
}
}
Expand Down

0 comments on commit e445385

Please sign in to comment.