Skip to content

Commit 0e01dad

Browse files
committed
improve URLError returned upon task cancellation
1 parent 17a35c2 commit 0e01dad

File tree

2 files changed

+15
-3
lines changed

2 files changed

+15
-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 = self.syncQ.sync { () -> Bool in
368+
guard self._state == .running || self._state == .suspended else { return true }
369+
self._state = .canceling
370+
return false
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 = self.originalRequest?.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()

Tests/Foundation/Tests/TestURLSession.swift

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1443,6 +1443,9 @@ class TestURLSession: LoopbackServerTest {
14431443
XCTAssertNotNil(error as? URLError)
14441444
if let urlError = error as? URLError {
14451445
XCTAssertEqual(urlError._nsError.code, NSURLErrorCancelled)
1446+
XCTAssertEqual(urlError.userInfo[NSURLErrorFailingURLErrorKey] as? URL, URL(string: urlString))
1447+
XCTAssertEqual(urlError.userInfo[NSURLErrorFailingURLStringErrorKey] as? String, urlString)
1448+
XCTAssertEqual(urlError.localizedDescription, "cancelled")
14461449
}
14471450

14481451
expect.fulfill()

0 commit comments

Comments
 (0)