Skip to content

Instantly share code, notes, and snippets.

@0xWDG
Created December 29, 2024 20:44
Show Gist options
  • Save 0xWDG/a97704ee96bedd8c1ddb5559397c173a to your computer and use it in GitHub Desktop.
Save 0xWDG/a97704ee96bedd8c1ddb5559397c173a to your computer and use it in GitHub Desktop.
extension View {
func showError(error: Binding<Error?>, buttonTitle: String = "OK") -> some View {
alert(
error.wrappedValue?.localizedDescription ?? "Unknown error",
isPresented: .constant(error.wrappedValue != nil)
) {
Button(buttonTitle) {
error.wrappedValue = nil
}
}
}
}
public struct CustomError: Error {
let message: String
}
extension CustomError: LocalizedError {
public var errorDescription: String? {
NSLocalizedString(message, comment: "")
}
}
import SwiftUI
struct ContentView: View {
@State private var error: Error?
var body: some View {
Text("Hi")
.task {
doSomething()
}
.showError(error $error)
}
func doSomething() {
do {
try something()
} catch {
self.error = error
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment