Skip to content

Commit d44d965

Browse files
committed
improve URLError returned upon task cancellation
1 parent 1c1e52a commit d44d965

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

Sources/FoundationNetworking/URLSession/URLSessionTask.swift

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -364,11 +364,20 @@ open class URLSessionTask : NSObject, NSCopying {
364364
*/
365365
open func cancel() {
366366
workQueue.sync {
367-
guard self.state == .running || self.state == .suspended else { return }
368-
self.state = .canceling
367+
let (canceled, request) = self.syncQ.sync { () -> (Bool, URLRequest?) in
368+
guard self._state == .running || self._state == .suspended else { return (true, nil)}
369+
_state = .canceling
370+
return (false, _currentRequest ?? originalRequest)
371+
}
372+
guard !canceled else { return }
369373
self._getProtocol { (urlProtocol) in
370374
self.workQueue.async {
371-
let urlError = URLError(_nsError: NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: nil))
375+
var info = [NSLocalizedDescriptionKey: "\(URLError.Code.cancelled)" as Any]
376+
if let url = request?.url {
377+
info[NSURLErrorFailingURLErrorKey] = url
378+
info[NSURLErrorFailingURLStringErrorKey] = url.absoluteString
379+
}
380+
let urlError = URLError(_nsError: NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: info))
372381
self.error = urlError
373382
if let urlProtocol = urlProtocol {
374383
urlProtocol.stopLoading()

0 commit comments

Comments
 (0)