Error protocol is an empty marker protocol. The cleanest reusable fix is a tiny struct conforming to LocalizedError so you can write throw RuntimeError("Custom message") and read it back via error.localizedDescription. For quick scripts, you can also use a single-case enum with an associated String or extend String to conform to LocalizedError.Why this happens
Developers coming to Swift from Java, Kotlin, C#, Python, or JavaScript usually look for an equivalent to throw new RuntimeException("Something went wrong") or throw new Error("Invalid input"). When you try to do that in Swift, you quickly discover that there is no built-in Error("message") initializer in the standard library.
In Swift, Error is an empty marker protocol with zero required properties or initializers. Any type—a struct, enum, or class—can conform to Error, which encourages strongly typed domain errors like NetworkError.timeout. While typed enums are great when a catch block needs to branch on specific failure modes, defining a brand-new enum for every one-off validation failure or internal sanity check adds unnecessary boilerplate.
There is a second catch that trips up developers even after they create a custom error type: calling error.localizedDescription on a plain Swift Error does not return your custom message. Instead, Foundation bridges the type to NSError and produces a generic fallback string like The operation couldn’t be completed. (MyApp.MyError error 0.). To make your custom string show up in logs and SwiftUI alerts automatically, your error type also needs to conform to LocalizedError from Foundation.
How to fix it
1. Define a reusable LocalizedError struct (Recommended)
The cleanest production-safe way to mimic throw RuntimeError("Custom message") across an entire app is to define a tiny wrapper struct once in your project. By conforming to both LocalizedError and CustomStringConvertible, your message works seamlessly whether callers inspect error.localizedDescription, String(describing: error), or print the error directly to the console.
import Foundation
struct RuntimeError: LocalizedError, CustomStringConvertible {
let message: String
init(_ message: String) {
self.message = message
}
var errorDescription: String? {
message
}
var description: String {
message
}
}
With those 15 lines in place, throwing and catching an ad-hoc error message looks natural anywhere in your codebase:
func parseUsername(_ rawInput: String) throws -> String {
let trimmed = rawInput.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else {
throw RuntimeError("Username cannot be empty.")
}
guard trimmed.count >= 3 else {
throw RuntimeError("Username must be at least 3 characters long.")
}
return trimmed
}
do {
let username = try parseUsername(" ")
print("Saved: \(username)")
} catch {
// Prints: Username cannot be empty.
print(error.localizedDescription)
}
Unlike extending built-in standard library types, RuntimeError belongs to your module. It will never collide with third-party Swift packages or trigger compiler warnings about retroactive protocol conformances.
2. Use a single-case enum with an associated String
If you prefer Swift’s conventional enum-based error modeling—or want to start with a general message case and gradually add structured cases later—create an enum with a String associated value.
import Foundation
enum AppError: LocalizedError {
case message(String)
var errorDescription: String? {
switch self {
case .message(let text):
return text
}
}
}
You can catch the specific case using pattern matching when you want direct access to the string, or catch it as any Error and rely on localizedDescription:
func loadConfiguration(from data: Data) throws {
guard !data.isEmpty else {
throw AppError.message("Configuration file is empty.")
}
}
// Option A: Pattern-match the specific enum case
do {
try loadConfiguration(from: Data())
} catch AppError.message(let reason) {
print("Config error: \(reason)")
} catch {
print("Unexpected error: \(error.localizedDescription)")
}
This approach shines when a feature starts simple (case message(String)) and later grows into explicit cases such as case unauthorized or case invalidStatusCode(Int) without forcing you to rewrite existing do / catch blocks.
3. Extend String to conform to LocalizedError (Quickest for scripts)
If you are writing a Swift command-line script, a Playground, or a quick prototype and want zero ceremony, you can make String itself conform to LocalizedError (which inherits from Error).
import Foundation
extension String: @retroactive Error {}
extension String: @retroactive LocalizedError {
public var errorDescription: String? {
self
}
}
(Note: If you are using an older Swift toolchain prior to Swift 6, omit the @retroactive attribute and write extension String: LocalizedError directly.)
Once added, any string literal or interpolated string becomes directly throwable:
func divide(_ numerator: Double, by denominator: Double) throws -> Double {
guard denominator != 0 else {
throw "Cannot divide \(numerator) by zero."
}
return numerator / denominator
}
do {
let result = try divide(10, by: 0)
print(result)
} catch {
print(error.localizedDescription) // Cannot divide 10.0 by zero.
}
Important caveat: Avoid shipping extension String: LocalizedError inside a shared framework or Swift Package Manager library. Because String is owned by the Swift standard library and LocalizedError is owned by Foundation, conforming one imported type to another imported protocol is a retroactive conformance. If two dependencies in the same app declare conflicting errorDescription implementations on String, runtime behavior becomes unpredictable. Stick to Fix 1 (RuntimeError) in shared modules and production apps.
4. Throw an NSError for Objective-C interoperability
If you do not want to declare any new types or extensions at all—or if your Swift function overrides or bridges to an Objective-C method expecting specific error domains and integer codes—you can throw NSError directly with NSLocalizedDescriptionKey.
import Foundation
func validatePort(_ port: Int) throws {
guard (1...65535).contains(port) else {
throw NSError(
domain: "com.example.networking",
code: 1001,
userInfo: [NSLocalizedDescriptionKey: "Port \(port) is out of the valid 1–65535 range."]
)
}
}
Because constructing that dictionary inline gets verbose, a short static factory helper keeps call sites tidy while preserving full NSError compatibility:
import Foundation
extension NSError {
static func custom(_ message: String, domain: String = "AppErrorDomain", code: Int = -1) -> NSError {
NSError(domain: domain, code: code, userInfo: [NSLocalizedDescriptionKey: message])
}
}
// Usage:
throw NSError.custom("Disk cache directory is missing.")
How to prevent it
- Always implement
LocalizedError, not justError: Implementingvar errorDescription: String?ensureserror.localizedDescriptionreturns your message instead ofThe operation couldn’t be completed.in alerts and crash breadcrumbs. - Keep retroactive
Stringextensions out of libraries: Never exposeextension String: Errororextension String: LocalizedErrorfrom a Swift package; use an internal or public wrapperstructinstead. - Upgrade string errors when callers need branching logic: If you ever catch yourself checking
if error.localizedDescription.contains("timeout"), replace that string message with a dedicatedenumcase so the compiler enforces exhaustive handling. - Reserve
fatalError(_:)for programmer bugs: Never usefatalError("message")orpreconditionFailure("message")as a substitute forthrowwhen handling bad user input, missing files, or network responses—those functions unconditionally crash the app.
FAQ
Why does error.localizedDescription show “The operation couldn’t be completed” instead of my message?
Conforming to Swift’s Error protocol alone does not tell Foundation how to extract a human-readable message from your type, so Foundation synthesizes a generic fallback string using the type name and an error code. Conform your error type to LocalizedError (from import Foundation) and return your string from var errorDescription: String? to display the exact message.
What is the difference between throwing an Error and calling fatalError("message")?
Throwing an Error with throw unwinds only to the nearest catch block, allowing your app to recover gracefully or display an alert to the user. Calling fatalError("message") immediately terminates the process and generates a crash log, so it should only be used for unrecoverable invariant violations.
Can I use Swift typed throws with a custom message struct?
Yes. In Swift 6 and later, you can declare func parseUsername(_ input: String) throws(RuntimeError) -> String so callers know at compile time that every thrown error is a RuntimeError and can read error.message directly inside catch without type casting.
Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.