Handle errors in (most) shared code

Two outliers to come back to are:

- the LocalStoreManager, where we can’t set a current error in the WriteFreelyModel in methods that can’t throw
- the CollectionListModel, where the initializer can’t throw because we use it as a property initializer in CollectionListView
This commit is contained in:
Angelo Stavrow 2022-05-26 08:08:12 -04:00
parent c5b611b39e
commit 15f84b04c0
No known key found for this signature in database
GPG Key ID: 1A49C7064E060EEE
4 changed files with 17 additions and 6 deletions

View File

@ -40,8 +40,8 @@ extension WriteFreelyModel {
client = nil
DispatchQueue.main.async {
self.account.logout()
LocalStorageManager.standard.purgeUserCollections()
do {
try LocalStorageManager.standard.purgeUserCollections()
try self.posts.purgePublishedPosts()
} catch {
self.currentError = error
@ -59,8 +59,8 @@ extension WriteFreelyModel {
client = nil
DispatchQueue.main.async {
self.account.logout()
LocalStorageManager.standard.purgeUserCollections()
do {
try LocalStorageManager.standard.purgeUserCollections()
try self.posts.purgePublishedPosts()
} catch {
self.currentError = error

View File

@ -23,19 +23,19 @@ final class LocalStorageManager {
do {
try container.viewContext.save()
} catch {
print(LocalStoreError.couldNotSaveContext.localizedDescription)
fatalError(LocalStoreError.couldNotSaveContext.localizedDescription)
}
}
}
func purgeUserCollections() {
func purgeUserCollections() throws {
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "WFACollection")
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try container.viewContext.executeAndMergeChanges(using: deleteRequest)
} catch {
print(LocalStoreError.couldNotPurgeCollections.localizedDescription)
throw LocalStoreError.couldNotPurgeCollections
}
}

View File

@ -20,7 +20,7 @@ class CollectionListModel: NSObject, ObservableObject {
list = collectionsController.fetchedObjects ?? []
} catch {
// FIXME: Errors cannot be thrown out of the CollectionListView property initializer
print("Failed to fetch collections!")
fatalError(LocalStoreError.couldNotFetchCollections.localizedDescription)
}
}
}

View File

@ -2,6 +2,7 @@ import SwiftUI
struct CollectionListView: View {
@EnvironmentObject var model: WriteFreelyModel
@EnvironmentObject var errorHandling: ErrorHandling
@ObservedObject var collections = CollectionListModel(
managedObjectContext: LocalStorageManager.standard.container.viewContext
)
@ -40,6 +41,16 @@ struct CollectionListView: View {
self.model.editor.showAllPostsFlag = model.showAllPosts
}
}
.onChange(of: model.hasError) { value in
if value {
if let error = model.currentError {
self.errorHandling.handle(error: error)
} else {
self.errorHandling.handle(error: AppError.genericError())
}
model.hasError = false
}
}
}
}