Skip to content
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

Improve catching of Swift Errors. #53

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
10 changes: 9 additions & 1 deletion Disk.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
10F3C7041F23D9C9006D42EF /* Disk+Data.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10F3C7031F23D9C9006D42EF /* Disk+Data.swift */; };
10F3C7061F23D9E0006D42EF /* Disk+[Data].swift in Sources */ = {isa = PBXBuildFile; fileRef = 10F3C7051F23D9E0006D42EF /* Disk+[Data].swift */; };
10F3C7081F23DAF2006D42EF /* Message.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10F3C7071F23DAF2006D42EF /* Message.swift */; };
261E777E2178916800B7DFB6 /* DiskErrors.m in Sources */ = {isa = PBXBuildFile; fileRef = 261E777D2178916800B7DFB6 /* DiskErrors.m */; };
261E777F21789EB900B7DFB6 /* DiskErrors.h in Headers */ = {isa = PBXBuildFile; fileRef = 261E777C2178912C00B7DFB6 /* DiskErrors.h */; settings = {ATTRIBUTES = (Public, ); }; };
/* End PBXBuildFile section */

/* Begin PBXContainerItemProxy section */
Expand Down Expand Up @@ -55,6 +57,8 @@
10F3C7031F23D9C9006D42EF /* Disk+Data.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Disk+Data.swift"; sourceTree = "<group>"; };
10F3C7051F23D9E0006D42EF /* Disk+[Data].swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Disk+[Data].swift"; sourceTree = "<group>"; };
10F3C7071F23DAF2006D42EF /* Message.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Message.swift; sourceTree = "<group>"; };
261E777C2178912C00B7DFB6 /* DiskErrors.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = DiskErrors.h; sourceTree = "<group>"; };
261E777D2178916800B7DFB6 /* DiskErrors.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = DiskErrors.m; sourceTree = "<group>"; };
/* End PBXFileReference section */

/* Begin PBXFrameworksBuildPhase section */
Expand Down Expand Up @@ -103,6 +107,8 @@
103FA3761F713332004C600F /* Disk+InternalHelpers.swift */,
103FA3781F713340004C600F /* Disk+VolumeInformation.swift */,
104611771F27B27E00BBDB3A /* Disk+Errors.swift */,
261E777C2178912C00B7DFB6 /* DiskErrors.h */,
261E777D2178916800B7DFB6 /* DiskErrors.m */,
109256591F247F7700B3C32A /* Disk+Helpers.swift */,
10F3C6FD1F23D9A4006D42EF /* Disk+Codable.swift */,
10F3C6FF1F23D9B1006D42EF /* Disk+UIImage.swift */,
Expand Down Expand Up @@ -132,6 +138,7 @@
isa = PBXHeadersBuildPhase;
buildActionMask = 2147483647;
files = (
261E777F21789EB900B7DFB6 /* DiskErrors.h in Headers */,
10F3C6F21F23D984006D42EF /* Disk.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
Expand Down Expand Up @@ -187,7 +194,7 @@
TargetAttributes = {
10F3C6E01F23D984006D42EF = {
CreatedOnToolsVersion = 9.0;
LastSwiftMigration = 0900;
LastSwiftMigration = 1010;
};
10F3C6E91F23D984006D42EF = {
CreatedOnToolsVersion = 9.0;
Expand Down Expand Up @@ -245,6 +252,7 @@
10F3C7041F23D9C9006D42EF /* Disk+Data.swift in Sources */,
103FA3791F713340004C600F /* Disk+VolumeInformation.swift in Sources */,
10F3C7001F23D9B1006D42EF /* Disk+UIImage.swift in Sources */,
261E777E2178916800B7DFB6 /* DiskErrors.m in Sources */,
104611781F27B27E00BBDB3A /* Disk+Errors.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
Expand Down
14 changes: 13 additions & 1 deletion DiskExample/DiskExample/ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ class ViewController: UIViewController {
@IBAction func retrieveTapped(_ sender: Any) {
// We'll keep things simple here by using try?, but it's good practice to handle Disk with do, catch, try blocks
// so you can make sure everything is going according to plan.
if let retrievedPosts = try? Disk.retrieve("posts.json", from: .documents, as: [Post].self) {
do {
let retrievedPosts = try Disk.retrieve("posts.json", from: .documents, as: [Post].self)
// If you Option+Click 'retrievedPosts' above, you'll notice that its type is [Post]
// Pretty neat, huh?

Expand All @@ -77,6 +78,17 @@ class ViewController: UIViewController {
self.resultsTextView.text = result

print("Retrieved posts from disk!")
} catch DiskError.noFileFound {
self.resultsTextView.text = "No file saved to disk yet!"
print ("No file found to retrieve posts from.")
} catch let error as NSError {
fatalError("""
Domain: \(error.domain)
Code: \(error.code)
Description: \(error.localizedDescription)
Failure Reason: \(error.localizedFailureReason ?? "")
Suggestions: \(error.localizedRecoverySuggestion ?? "")
""")
}
}

Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,8 @@ do {
if Disk.exists("posts.json", in: .documents) {
try Disk.remove("posts.json", from: .documents)
}
} catch DiskError.noFileFound {
// Pattern matching to catch specific errors.
} catch let error as NSError {
fatalError("""
Domain: \(error.domain)
Expand Down
15 changes: 2 additions & 13 deletions Sources/Disk+Errors.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,24 +23,13 @@
import Foundation

extension Disk {
public enum ErrorCode: Int {
case noFileFound = 0
case serialization = 1
case deserialization = 2
case invalidFileName = 3
case couldNotAccessTemporaryDirectory = 4
case couldNotAccessUserDomainMask = 5
case couldNotAccessSharedContainer = 6
}

public static let errorDomain = "DiskErrorDomain"

/// Create custom error that FileManager can't account for
static func createError(_ errorCode: ErrorCode, description: String?, failureReason: String?, recoverySuggestion: String?) -> Error {
static func createError(_ errorCode: DiskError.Code, description: String?, failureReason: String?, recoverySuggestion: String?) -> DiskError {
let errorInfo: [String: Any] = [NSLocalizedDescriptionKey : description ?? "",
NSLocalizedRecoverySuggestionErrorKey: recoverySuggestion ?? "",
NSLocalizedFailureReasonErrorKey: failureReason ?? ""]
return NSError(domain: errorDomain, code: errorCode.rawValue, userInfo: errorInfo) as Error
return NSError(domain: DiskErrorDomain, code: errorCode.rawValue, userInfo: errorInfo) as! DiskError
}
}

2 changes: 1 addition & 1 deletion Sources/Disk.h
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,4 @@ FOUNDATION_EXPORT double DiskVersionNumber;
//! Project version string for Disk.
FOUNDATION_EXPORT const unsigned char DiskVersionString[];


#import "DiskErrors.h"
24 changes: 24 additions & 0 deletions Sources/DiskErrors.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
//
// DiskErrors.h
// Disk
//
// Created by Sven Titgemeyer on 18.10.18.
// Copyright © 2018 Saoud Rizwan. All rights reserved.
//

#import <Foundation/Foundation.h>

/// Domain for Disk Errors.
///
/// Define Errors in Objective-C to get better Bridging between Swift/Objective-C.
/// Errors are imported as `DiskError` in Swift.
extern NSErrorDomain const DiskErrorDomain;
typedef NS_ERROR_ENUM(DiskErrorDomain, DiskError) {
DiskErrorNoFileFound = 0,
DiskErrorSerialization = 1,
DiskErrorDeserialization = 2,
DiskErrorInvalidFileName = 3,
DiskErrorCouldNotAccessTemporaryDirectory = 4,
DiskErrorCouldNotAccessUserDomainMask = 5,
DiskErrorCouldNotAccessSharedContainer = 6
};
11 changes: 11 additions & 0 deletions Sources/DiskErrors.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
//
// DiskErrors.m
// Disk
//
// Created by Sven Titgemeyer on 18.10.18.
// Copyright © 2018 Saoud Rizwan. All rights reserved.
//

#import "DiskErrors.h"

NSErrorDomain const DiskErrorDomain = @"DiskErrorDomain";
3 changes: 2 additions & 1 deletion Tests/DiskTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -805,7 +805,8 @@ class DiskTests: XCTestCase {
try Disk.append(oneMessage, to: "Folder/", in: .documents)
let _ = try Disk.retrieve("Folder/", from: .documents, as: [Message].self)
} catch let error as NSError {
XCTAssert(error.code == Disk.ErrorCode.invalidFileName.rawValue)
XCTAssert(error is DiskError)
XCTAssert(error.code == DiskError.invalidFileName.rawValue)
}
}

Expand Down