Good Errors #swiftlang

To raise an error, throw any instance that conforms to ErrorType. In the simplest case, create a struct and throw it, as in the following example.

public struct SomethingWentWrong : ErrorType {}
...something happens...
throw SomethingWentWrong()

In the best of all possible worlds, your diagnostics should read less like random fortune cookie paper slips and more like constructive pointers that explain your failure. Avoid:

public enum SomethingWentWrongError: ErrorType {
    case YouWillFindNewLove
    case AClosedMouthGathersNoFeet
    case CynicsAreFrustratedOptimists
    case IfEverythingIsComingYourWayYouAreInTheWrongLane

Good errors should be written for human consumption in a professional environment:

▪   Be clear. A good error message should establish what the issue is, the cause of the issue, the source of the issue, and how to resolve the issue. Take inspiration from Foundation and offer both failure reasons and recovery suggestions in your error feedback.

▪   Be precise. The more your error traces back to a specific fail point, the better able an end-programmer will be able to use it to fix their code or respond with runtime workarounds.

▪   Incorporate details. Swift errors enable you to create structures, associate values, and provide vital context about where and why things went wrong. Create more informative errors with details.

▪   Prefer clarity to concision. Don’t eliminate words just for the sake of short error messages. Yes: “Unable to access uninitialized data store” No: “Uninitialized”. At the same time, limit your explanations to the issue your error is dealing with. Avoid unneeded extras.

▪   Add support. When you incorporate API and documentation references, you further help explain the condition and support recovery. Links are good. Snippets can be good. Full documentation is unnecessary. Allow features like Quick Help to properly fill their role without attempting to usurp them.

▪   Avoid jargon, especially if your error may be consumed outside the context of your immediate working environment. When in doubt, prefer simpler and more common words to project-specific names.

▪   Be polite in your phrasing, in ways that do not insult your cubical mate, your manager, or the persons who developed the API you’re struggling with. Minimize humor. Humor travels poorly. An error message that’s meant to be self-deprecating may misfire at a future point.

Comments are closed.