Programming Search⌘K

Techniquecore

Replace error code with exception

Replace a special return value that signals an error with a thrown exception, in languages where exceptions are the normal way to report errors.

Family
refactoring
Intent
Keep the error out of the return value, and stop a caller from ignoring it.

Purpose

An error code is a special value, such as -1 or -23, that a function returns in place of its normal result. Error codes have three problems:

  • The caller can ignore the code, and the program goes on with a wrong value.
  • The code shares the return value with real results, so a valid result cannot use that value.
  • Each caller up the stack must check the code and pass it on, even when only one function far away can handle it.

In a language with exceptions, Replace error code with exception throws an exception in place of the code. The catalogue card has else return -23;. After the refactoring, it is else throw new OrderProcessingError(-23);.1 The exception goes up the stack to the nearest handler. A caller that does not handle it does not need any code for it. See Exception handling.

The language decides

This refactoring is right for JavaScript, Python, Java, C# and other languages where the standard library throws exceptions. It is wrong for Go and Rust. Do not apply it there.

  • Go. The Go FAQ says: "We believe that coupling exceptions to a control structure, as in the try-catch-finally idiom, results in convoluted code. It also tends to encourage programmers to label too many ordinary errors, such as failing to open a file, as exceptional."4 The Go Blog says: "Go code uses error values to indicate an abnormal state."5 The Go form of this refactoring is to replace the special value with a second return value of type error.
  • Rust. The Rust book says: "Rust doesn’t have exceptions. Instead, it has the type Result<T, E> for recoverable errors and the panic! macro that stops execution when the program encounters an unrecoverable error."6 It adds that "when failure is expected, it’s more appropriate to return a Result than to make a panic! call."7 The Rust form is to return Result<T, E>.

In both languages, the change removes the special value from the normal result, as the exception does, and the type of the result shows that the call can fail. See Errors as values and Panics.

Steps

  1. Make an exception class for the error, or choose one that exists. Do not use the most general class, so that a handler can catch only this error.
  2. Find each caller that checks the code. Change each one: put the call in a try block, and move the code that handles the error into the catch block. Callers that only passed the code on need no handler.
  3. Change the function to throw the exception in place of the code.
  4. Remove the checks of the code that are now dead. Test.

Example

localShippingRules returns a code when the country has no shipping data. Each caller must check for the code. After the refactoring, the function throws an OrderProcessingError, and only the top level catches it.

import assert from "node:assert/strict";

const countryData = { shippingRules: { PT: { flat: 5 } } };

function localShippingRulesBefore(country) {
  const data = countryData.shippingRules[country];
  if (data) return data;
  else return -23;
}

class OrderProcessingError extends Error {
  constructor(errorCode) {
    super(`order processing error ${errorCode}`);
    this.code = errorCode;
  }
  get name() { return "OrderProcessingError"; }
}

function localShippingRules(country) {
  const data = countryData.shippingRules[country];
  if (data) return data;
  else throw new OrderProcessingError(-23);
}

// Before: each caller must check the code.
assert.equal(localShippingRulesBefore("XX"), -23);

// After: the code that does not handle the error has no checks.
function shippingCost(country) {
  return localShippingRules(country).flat;
}

const status = [];
for (const country of ["PT", "XX"]) {
  try {
    status.push(shippingCost(country));
  } catch (e) {
    if (e instanceof OrderProcessingError) status.push(e.code);
    else throw e;
  }
}
assert.deepEqual(status, [5, -23]);
console.log(status);
Output
[ 5, -23 ]

The handler catches only OrderProcessingError, and it throws any other error again.

Language What the example shows
JavaScript the code -23 replaced with throw new OrderProcessingError(-23), as above
Python the same change; the function raises a subclass of Exception, and the handler catches only that subclass
Go not an exception: the code is replaced with a second return value of type error, and the caller checks it with errors.As
PythonGitHub
country_data = {"shipping_rules": {"PT": {"flat": 5}}}


def local_shipping_rules_before(country: str):
    data = country_data["shipping_rules"].get(country)
    return data if data else -23


class OrderProcessingError(Exception):
    def __init__(self, code: int) -> None:
        super().__init__(f"order processing error {code}")
        self.code = code


def local_shipping_rules(country: str) -> dict:
    data = country_data["shipping_rules"].get(country)
    if data:
        return data
    raise OrderProcessingError(-23)


def shipping_cost(country: str) -> int:
    return local_shipping_rules(country)["flat"]


assert local_shipping_rules_before("XX") == -23
status = []
for country in ["PT", "XX"]:
    try:
        status.append(shipping_cost(country))
    except OrderProcessingError as e:
        status.append(e.code)
assert status == [5, -23]
print(status)
Output
[5, -23]
package main

import (
	"errors"
	"fmt"
)

type ShippingRules struct{ Flat int }

var shippingRules = map[string]ShippingRules{"PT": {Flat: 5}}

// Before: a special value in the normal result.
func localShippingRulesBefore(country string) (ShippingRules, int) {
	if r, ok := shippingRules[country]; ok {
		return r, 0
	}
	return ShippingRules{}, -23
}

// In Go, the code moves into a value of type error, not into a panic.
type OrderProcessingError struct{ Code int }

func (e *OrderProcessingError) Error() string {
	return fmt.Sprintf("order processing error %d", e.Code)
}

func localShippingRules(country string) (ShippingRules, error) {
	if r, ok := shippingRules[country]; ok {
		return r, nil
	}
	return ShippingRules{}, &OrderProcessingError{Code: -23}
}

func shippingCost(country string) (int, error) {
	r, err := localShippingRules(country)
	if err != nil {
		return 0, fmt.Errorf("shipping cost for %s: %w", country, err)
	}
	return r.Flat, nil
}

func main() {
	if _, code := localShippingRulesBefore("XX"); code != -23 {
		panic("mismatch")
	}
	var status []int
	for _, country := range []string{"PT", "XX"} {
		cost, err := shippingCost(country)
		var ope *OrderProcessingError
		if errors.As(err, &ope) {
			status = append(status, ope.Code)
			continue
		}
		status = append(status, cost)
	}
	fmt.Println(status)
}
Output
[5 -23]

When to use

  • A language with exceptions, where callers expect them.
  • An error that most callers cannot handle. The exception passes through them with no code.
  • A special value that a valid result could also have. For example, -1 from a function that can also return negative numbers.

Pitfalls

Expected results are not errors. If a caller must check a case at each call, such as a key that is not in a map, a special result or an optional value can be clearer than an exception. For a case that the caller can check before the call, see Replace Exception with Precheck.

Catching too much. A handler that catches every exception also hides bugs, such as a TypeError from a wrong name. Catch the class of the error, as the example does.

Exceptions are invisible in the signature. In JavaScript, Python and C#, the signature does not list the exceptions that a function can throw. Document them, or the callers do not know what to catch.

Go and Rust. See the section above. An exception-style panic in Go or Rust for an ordinary error goes against the advice of both languages.47

Tools that do it

No IDE has one action for this refactoring. The steps change each caller, so they are done by hand.

The catalogue lists the refactoring in the first edition, the second edition and the Ruby edition, with the tags refactoring-apis and errors.2 In the second edition it is in Chapter 11, Refactoring APIs.3

References

  1. Martin Fowler, Catalog of Refactorings, Replace Error Code with Exception, the entry, the ShippingRules sketch
  2. Martin Fowler, Catalog of Refactorings, index, the entry replaceErrorCodeWithException, its books and tags
  3. Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 11, Refactoring APIs, Replace Error Code with Exception
  4. The Go Programming Language, Frequently Asked Questions, Why does Go not have exceptions?
  5. Andrew Gerrand, Error handling and Go, The Go Blog, 12 July 2011, the first section
  6. The Rust Programming Language, Chapter 9, Error Handling, the first paragraphs
  7. The Rust Programming Language, Chapter 9.3, To panic! or Not to panic!, the first paragraphs and Guidelines for Error Handling

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/N3VZ77/text.yaml