You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何控制Swift自定义错误的.localizedDescription属性?

Fixing Custom Runtime Error Output in Swift

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, calling print(error) would default to the verbose struct representation (like MyApp.RuntimeError(...)). Overriding description ensures plain, readable output when you print the error directly.
  • CustomDebugStringConvertible: Swift uses this property for uncaught top-level error reports. By setting it to your localizedDescription, you'll get clean, direct error messages instead of the struct's debug-style dump.
  • LocalizedError: Your original implementation stays intact, so error.localizedDescription will still return your custom message for user-facing contexts (like UI alerts).

Test It Out

  1. 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.

  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:31:19