Last active
January 13, 2025 03:01
-
-
Save nezhyborets/9c64e07f367530223247480682eb5bc5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// NSAlert+Error.swift | |
// | |
// Created by Oleksii Nezhyborets on 18.12.2024. | |
// | |
import AppKit | |
import Photos | |
@available(macOS 10.15, *) | |
extension NSAlert { | |
static func informativeAlert(forError error: Error, function: StaticString = #function) -> NSAlert { | |
let alert: NSAlert | |
switch error { | |
case let photosError as PHPhotosError: | |
alert = .init() | |
alert.messageText = photosError.localizedDescription | |
let basicInfo = ["Function: \(function)", "Error Code: \(photosError.code)"].joined(separator: "\n") | |
let userInfo = photosError.userInfo.map { key, value in | |
"\(key): \(value)" | |
}.joined(separator: "\n") | |
let errorUserInfo = photosError.errorUserInfo.map { key, value in | |
"\(key): \(value)" | |
}.joined(separator: "\n") | |
alert.informativeText = [basicInfo, userInfo, errorUserInfo].joined(separator: "\n\n") | |
case let nsError as NSError: | |
alert = .init() | |
alert.messageText = nsError.localizedDescription | |
let basicString = ["Function: \(function)", "Error Domain: \(nsError.domain)", "Error Code: \(nsError.code)"] | |
.joined(separator: "\n") | |
let userInfoString = nsError.userInfo.map { key, value in | |
"\(key): \(value)" | |
}.joined(separator: "\n\n") | |
alert.informativeText = [basicString, userInfoString].joined(separator: "\n\n") | |
case let localizedError as LocalizedError: | |
alert = .init() | |
alert.messageText = localizedError.localizedDescription | |
let dict = [ | |
"Function": function.string, | |
"Error description": localizedError.errorDescription, | |
"Failure reason": localizedError.failureReason, | |
"Recovery suggestion": localizedError.recoverySuggestion | |
] | |
let localizedErrorString = dict.map { key, value in | |
"\(key): \(value ?? "nil")" | |
}.joined(separator: "\n") | |
if let recoverableError = localizedError as? RecoverableError { | |
let recoverableErrorString = (["Recovery options:"] + recoverableError.recoveryOptions) | |
.joined(separator: "\n") | |
alert.informativeText = [localizedErrorString, recoverableErrorString] | |
.joined(separator: "\n\n") | |
} else { | |
alert.informativeText = localizedErrorString | |
} | |
default: | |
alert = .init(error: error) | |
} | |
return alert | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment