Skip to content

[5.3] improve URLError returned upon task cancellation #2844

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 17, 2020
Merged
Show file tree
Hide file tree
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
15 changes: 12 additions & 3 deletions Sources/FoundationNetworking/URLSession/URLSessionTask.swift
Original file line number Diff line number Diff line change
Expand Up @@ -364,11 +364,20 @@ open class URLSessionTask : NSObject, NSCopying {
*/
open func cancel() {
workQueue.sync {
guard self.state == .running || self.state == .suspended else { return }
self.state = .canceling
let canceled = self.syncQ.sync { () -> Bool in
guard self._state == .running || self._state == .suspended else { return true }
self._state = .canceling
return false
}
guard !canceled else { return }
self._getProtocol { (urlProtocol) in
self.workQueue.async {
let urlError = URLError(_nsError: NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: nil))
var info = [NSLocalizedDescriptionKey: "\(URLError.Code.cancelled)" as Any]
if let url = self.originalRequest?.url {
info[NSURLErrorFailingURLErrorKey] = url
info[NSURLErrorFailingURLStringErrorKey] = url.absoluteString
}
let urlError = URLError(_nsError: NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: info))
self.error = urlError
if let urlProtocol = urlProtocol {
urlProtocol.stopLoading()
Expand Down
3 changes: 3 additions & 0 deletions Tests/Foundation/Tests/TestURLSession.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1443,6 +1443,9 @@ class TestURLSession: LoopbackServerTest {
XCTAssertNotNil(error as? URLError)
if let urlError = error as? URLError {
XCTAssertEqual(urlError._nsError.code, NSURLErrorCancelled)
XCTAssertEqual(urlError.userInfo[NSURLErrorFailingURLErrorKey] as? URL, URL(string: urlString))
XCTAssertEqual(urlError.userInfo[NSURLErrorFailingURLStringErrorKey] as? String, urlString)
XCTAssertEqual(urlError.localizedDescription, "cancelled")
}

expect.fulfill()
Expand Down