如何控制Swift自定义错误的.localizedDescription属性?
Hey there! Let's tackle this custom error output issue you're facing in Swift. I've run into similar frustrations before, so I know exactly what you're dealing with.
Your current RuntimeError struct implements LocalizedError, but Swift's default behavior for error reporting (especially at the top level) and printing errors doesn't always prioritize the localizedDescription out of the box. Let's break down the fixes step by step.
Updated RuntimeError Implementation
struct RuntimeError: LocalizedError, CustomStringConvertible, CustomDebugStringConvertible { let localizedDescription: String init(_ str: String) { localizedDescription = str } // Makes print(error) output your actual message instead of generic struct text var description: String { localizedDescription } // Fixes top-level fatal error output to show your message directly var debugDescription: String { localizedDescription } }
What Each Fix Does
CustomStringConvertible: Without this, callingprint(error)would default to the verbose struct representation (likeMyApp.RuntimeError(...)). Overridingdescriptionensures plain, readable output when you print the error directly.CustomDebugStringConvertible: Swift uses this property for uncaught top-level error reports. By setting it to yourlocalizedDescription, you'll get clean, direct error messages instead of the struct's debug-style dump.LocalizedError: Your original implementation stays intact, soerror.localizedDescriptionwill still return your custom message for user-facing contexts (like UI alerts).
Test It Out
Top-level throw:
throw RuntimeError("Something went wrong with the operation!")Now you'll see:
Fatal error: Error raised at top level: Something went wrong with the operation!instead of the verbose struct description.Catch and print:
do { throw RuntimeError("Oops, an unexpected error occurred") } catch { print(error) // Outputs: Oops, an unexpected error occurred print(error.localizedDescription) // Outputs: Oops, an unexpected error occurred }
Bonus: Enhanced Localized Error Support
If you want to add user-friendly recovery suggestions (common in macOS/iOS apps), extend the implementation to use all LocalizedError properties:
struct RuntimeError: LocalizedError, CustomStringConvertible, CustomDebugStringConvertible { let message: String let recoveryHint: String? init(_ message: String, recoveryHint: String? = nil) { self.message = message self.recoveryHint = recoveryHint } var localizedDescription: String { message } var errorDescription: String? { message } var recoverySuggestion: String? { recoveryHint } var description: String { message } var debugDescription: String { message } }
This makes your error fully compliant with Apple's error handling patterns, perfect for integrating with system UI components.
内容的提问来源于stack exchange,提问作者natevw

