Created
December 29, 2024 20:44
-
-
Save 0xWDG/a97704ee96bedd8c1ddb5559397c173a 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
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: "") | |
} | |
} |
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
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