Programming Search⌘K

Taskcore

Wrap an error with context

Also called exception chaining, chained exceptions, error wrapping, add context to an error, inner exception, nested exception, raise from.

Catch the error of a parser, add the place of the bad setting, and throw or return a new error that keeps the first one as its cause, so a caller can still find it.

Task

Catch an error from a lower level, add what the current level knows, and keep the first error. The function parse_port(text) reads a TCP port number. It fails with the message "not a number: 'TEXT'" or "out of range: TEXT". It does not know where the text came from. The function read_port(where, text) calls it. On an error, it makes a new error with the message "WHERE: read port" and keeps the error of parse_port as the cause.

The function check_setting(where, text) calls read_port. It returns "port N" on success. On an error, it returns "error: " and the messages of the error and its causes, joined with ": ". For example:

  • check_setting("app.conf:3", "8080") is "port 8080",
  • check_setting("app.conf:3", "x") is "error: app.conf:3: read port: not a number: 'x'".

The message alone could carry the context. The point of a wrap is that the cause stays an object, so a program can still test its type or its value. Error propagation explains why errors go up the call stack. This task is one step of that path. Define a custom error type makes the type of the outer error.

Solutions

Language The wrap The cause The next step in the chain
Python raise ConfigError(...) from e1 e.__cause__2 e.__cause__
JavaScript, TypeScript new Error(msg, { cause: e })3 e.cause3 e.cause
Java new ConfigException(msg, e)4 e.getCause()4 getCause()
C# new ConfigException(msg, e) e.InnerException5 InnerException
C++ std::throw_with_nested(...)6 std::rethrow_if_nested(e)7 a catch around rethrow_if_nested
Go fmt.Errorf("...: %w", err)8 errors.Is, errors.As8 in the message
Rust a struct with a source() method9 e.source()9 source()
C a new message with the context in front the code none
Bash a new message with the context in front the exit status none
  • Python. "To indicate that an exception is a direct consequence of another, the raise statement allows an optional from clause"1. The expression after from "will be set as cause on the raised exception"2. The traceback then shows both exceptions. The solution follows __cause__ to build the message.
  • JavaScript and TypeScript. "The cause data property of an Error instance indicates the specific original cause of the error. It is used when catching and re-throwing an error with a more-specific or useful error message in order to still have access to the original error"3. The solution passes { cause: e } to the constructor and follows cause while it is an Error, because "The value of cause can be of any type"3.
  • Java. "An application often responds to an exception by throwing another exception. In effect, the first exception causes the second exception"4. Throwable has the constructor Throwable(String, Throwable), and "getCause returns the exception that caused the current exception"4. ConfigException passes both arguments to super.
  • C#. "When an exception X is thrown as a direct result of a previous exception Y, the InnerException property of X should contain a reference to Y"5. ConfigException passes the inner exception to the constructor of Exception, and the solution follows InnerException.
  • C++. std::throw_with_nested(t) throws an exception that is derived from both std::nested_exception and the type of t. "The default constructor of the nested_exception base class calls std::current_exception, capturing the currently handled exception object"6. So the call must be inside the catch block. std::rethrow_if_nested(e) throws the nested exception again, if e has one7. The solution catches it and calls itself to walk the chain.
  • Go. "In Go 1.13, the fmt.Errorf function supports a new %w verb. When this verb is present, the error returned by fmt.Errorf will have an Unwrap method returning the argument of %w"8. "Wrapping an error with %w makes it available to errors.Is and errors.As"8. The message of the new error already has the message of the old error, so the solution prints err.Error(). The test finds ErrNotANumber with errors.Is.
  • Rust. "Errors may provide cause information"9, with Error::source(). ConfigError keeps the ParseError in a field and returns it from source. Its Display shows only the context, and a loop over source() builds the full message. The anyhow crate does the same work with a method: context on a Result adds a message, and its report prints the cause after "Caused by:"10.
  • C. C has no exception objects and no chain. read_port writes "WHERE: read port: " in front of the message of parse_port and returns the same code. A caller can still test the code, but the cause is now only text.
  • Bash. The same idea as C. read_port puts the context in front of ERROR_MESSAGE and returns the status of parse_port. Call it without $( ), because a command substitution runs in a subshell, and a command there "cannot affect the shell’s execution environment"11.

The cause at work

In Go, the wrapped error of strconv.Atoi is still there under the context. errors.As gets the value with its fields, and errors.Is finds the sentinel error inside it:

package main

import (
	"errors"
	"fmt"
	"strconv"
)

func readPort(where, text string) (int, error) {
	port, err := strconv.Atoi(text)
	if err != nil {
		return 0, fmt.Errorf("%s: read port: %w", where, err)
	}
	return port, nil
}

func main() {
	_, err := readPort("app.conf:3", "x")
	fmt.Println(err)
	var numErr *strconv.NumError
	if errors.As(err, &numErr) {
		fmt.Println("cause:", numErr.Func, numErr.Num, numErr.Err)
	}
	fmt.Println("syntax error:", errors.Is(err, strconv.ErrSyntax))
}
Output
app.conf:3: read port: strconv.Atoi: parsing "x": invalid syntax
cause: Atoi x invalid syntax
syntax error: true

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • empty: the empty text is "not a number: ''". The quotes show that the text is empty.
  • zero and largest: 0 is out of range, and 65535 is the largest port.
  • leading-space and negative: a space or a sign is not a digit.
  • overflow: twenty digits are more than a 64-bit integer can hold. The solutions stop when the value goes above 65535, so the cause is "out of range".

Pitfalls

  • A wrap that drops the cause. In Go, %w and %v give the same message: "In all other ways, %w is identical to %v"8. But only %w keeps the cause:

This code runs but gives a wrong answer on purpose.

package main

import (
	"errors"
	"fmt"
)

var ErrNotANumber = errors.New("not a number")

func readPort(where string) error {
	err := fmt.Errorf("%w: 'x'", ErrNotANumber)
	return fmt.Errorf("%s: read port: %v", where, err)
}

func main() {
	err := readPort("app.conf:3")
	fmt.Println(err)
	fmt.Println("not a number:", errors.Is(err, ErrNotANumber))
}
Output
app.conf:3: read port: not a number: 'x'
not a number: false

The same mistake in Java is new ConfigException(where + ": " + e.getMessage()). The message looks right, but getCause() returns null, and the stack trace of the first exception is lost.

  • The cause two times. The Rust documentation says that "the underlying error should be either returned by the outer error’s Error::source(), or rendered by the outer error’s Display implementation, but not both"9. Here Display shows the cause, and source returns it too, so a loop over the chain prints it two times:

This code runs but gives a wrong answer on purpose.

use std::error::Error;
use std::fmt;

#[derive(Debug)]
struct ParseError(String);

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "not a number: '{}'", self.0)
    }
}

impl Error for ParseError {}

#[derive(Debug)]
struct ConfigError {
    place: String,
    cause: ParseError,
}

impl fmt::Display for ConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: read port: {}", self.place, self.cause)
    }
}

impl Error for ConfigError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(&self.cause)
    }
}

fn main() {
    let e = ConfigError { place: "app.conf:3".to_string(), cause: ParseError("x".to_string()) };
    let mut message = e.to_string();
    let mut cur = e.source();
    while let Some(s) = cur {
        message = format!("{message}: {s}");
        cur = s.source();
    }
    println!("{message}");
}
Output
app.conf:3: read port: not a number: 'x': not a number: 'x'

Pick one: put the cause in Display, or return it from source.

  • A hidden cause. In Python, raise ConfigError(...) from None "effectively replaces the old exception with the new one for display purposes"2. The traceback then shows only the new exception. Use from None only when the cause does not help the reader.
  • A cause that leaks the inside. A wrapped cause becomes part of what callers can test. The Go blog says: "Wrap an error to expose it to callers. Do not wrap an error when doing so would expose implementation details"8. When the cause is an internal detail, put its text in the message and do not wrap it.

Code

The build runs the native tests of each language in a pinned toolchain.

check_setting.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/wrap-an-error-with-context/.


class ConfigError(Exception):
    """A setting in a configuration file is bad."""


def parse_port(text: str) -> int:
    """Return the port number in text, or raise ValueError."""
    if text == "" or any(c not in "0123456789" for c in text):
        raise ValueError(f"not a number: '{text}'")
    port = int(text)
    if not 1 <= port <= 65535:
        raise ValueError(f"out of range: {text}")
    return port


def read_port(where: str, text: str) -> int:
    """Return the port number, or raise ConfigError with the ValueError as its cause."""
    try:
        return parse_port(text)
    except ValueError as e:
        raise ConfigError(f"{where}: read port") from e


def chain(e: BaseException) -> str:
    """Join the message of e and the messages of its causes."""
    parts = [str(e)]
    while e.__cause__ is not None:
        e = e.__cause__
        parts.append(str(e))
    return ": ".join(parts)


def check_setting(where: str, text: str) -> str:
    """Return "port N", or "error: " and the chain of messages."""
    try:
        return f"port {read_port(where, text)}"
    except ConfigError as e:
        return f"error: {chain(e)}"
test_check_setting.py 30 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/wrap-an-error-with-context/.

import pytest

from check_setting import ConfigError, check_setting, read_port

CASES = {
    "valid": ("app.conf:3", "8080", "port 8080"),
    "not-a-number": ("app.conf:3", "x", "error: app.conf:3: read port: not a number: 'x'"),
    "too-large": ("app.conf:7", "70000", "error: app.conf:7: read port: out of range: 70000"),
    "empty": ("app.conf:1", "", "error: app.conf:1: read port: not a number: ''"),
    "zero": ("app.conf:2", "0", "error: app.conf:2: read port: out of range: 0"),
    "largest": ("app.conf:2", "65535", "port 65535"),
    "leading-space": ("app.conf:4", " 80", "error: app.conf:4: read port: not a number: ' 80'"),
    "overflow": ("app.conf:5", "99999999999999999999", "error: app.conf:5: read port: out of range: 99999999999999999999"),
    "negative": ("app.conf:6", "-1", "error: app.conf:6: read port: not a number: '-1'"),
}


@pytest.mark.parametrize("name", CASES)
def test_check_setting(name):
    where, text, want = CASES[name]
    assert check_setting(where, text) == want


def test_cause():
    with pytest.raises(ConfigError) as info:
        read_port("app.conf:3", "x")
    assert isinstance(info.value.__cause__, ValueError)
check_setting.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-an-error-with-context/.

#include "check_setting.hpp"

#include <algorithm>
#include <stdexcept>

int parse_port(const std::string &text) {
    if (text.empty() || !std::all_of(text.begin(), text.end(), [](char c) { return c >= '0' && c <= '9'; })) {
        throw std::invalid_argument("not a number: '" + text + "'");
    }
    long value = 0;
    for (char c : text) {
        value = value * 10 + (c - '0');
        if (value > 65535) {
            throw std::out_of_range("out of range: " + text);
        }
    }
    if (value == 0) {
        throw std::out_of_range("out of range: " + text);
    }
    return static_cast<int>(value);
}

int read_port(const std::string &where, const std::string &text) {
    try {
        return parse_port(text);
    } catch (const std::logic_error &) {
        // throw_with_nested keeps the exception that is handled now as the
        // nested exception of the new one.
        std::throw_with_nested(std::runtime_error(where + ": read port"));
    }
}

std::string chain(const std::exception &e) {
    std::string message = e.what();
    try {
        std::rethrow_if_nested(e);
    } catch (const std::exception &inner) {
        message += ": " + chain(inner);
    }
    return message;
}

std::string check_setting(const std::string &where, const std::string &text) {
    try {
        int port = read_port(where, text);
        return "port " + std::to_string(port);
    } catch (const std::runtime_error &e) {
        return "error: " + chain(e);
    }
}
check_setting.hpp 21 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-an-error-with-context/.

#pragma once

#include <exception>
#include <string>

// parse_port returns the port number in text. It throws std::invalid_argument
// or std::out_of_range.
int parse_port(const std::string &text);

// read_port returns the port number. On an error, it throws a
// std::runtime_error with the place, nested with the error of parse_port.
int read_port(const std::string &where, const std::string &text);

// chain joins the message of e and the messages of the nested exceptions.
std::string chain(const std::exception &e);

// check_setting returns "port N", or "error: " and the chain of messages.
std::string check_setting(const std::string &where, const std::string &text);
test_check_setting.cpp 51 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-an-error-with-context/.

#include "check_setting.hpp"

#include <iostream>
#include <stdexcept>
#include <string>
#include <string_view>

static int failures = 0;

static void check(std::string_view name, const std::string &where, const std::string &text, const std::string &want) {
    std::string got = check_setting(where, text);
    if (got != want) {
        std::cerr << "case " << name << " failed: got " << got << "\n";
        failures++;
    }
}

int main() {
    check("valid", "app.conf:3", "8080", "port 8080");
    check("not-a-number", "app.conf:3", "x", "error: app.conf:3: read port: not a number: 'x'");
    check("too-large", "app.conf:7", "70000", "error: app.conf:7: read port: out of range: 70000");
    check("empty", "app.conf:1", "", "error: app.conf:1: read port: not a number: ''");
    check("zero", "app.conf:2", "0", "error: app.conf:2: read port: out of range: 0");
    check("largest", "app.conf:2", "65535", "port 65535");
    check("leading-space", "app.conf:4", " 80", "error: app.conf:4: read port: not a number: ' 80'");
    check("overflow", "app.conf:5", "99999999999999999999", "error: app.conf:5: read port: out of range: 99999999999999999999");
    check("negative", "app.conf:6", "-1", "error: app.conf:6: read port: not a number: '-1'");

    bool nested = false;
    try {
        read_port("app.conf:3", "x");
    } catch (const std::runtime_error &e) {
        try {
            std::rethrow_if_nested(e);
        } catch (const std::invalid_argument &) {
            nested = true;
        }
    }
    if (!nested) {
        std::cerr << "case cause failed\n";
        failures++;
    }
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
CheckSetting.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-an-error-with-context/.

/** Reads a port setting and wraps the error of the parser with the place of the setting. */
final class CheckSetting {
  private CheckSetting() {}

  /** A setting in a configuration file is bad. */
  static final class ConfigException extends Exception {
    // Exception is Serializable, and javac -Xlint:serial asks for this field.
    private static final long serialVersionUID = 1L;

    ConfigException(String message, Throwable cause) {
      super(message, cause);
    }
  }

  /** Returns the port number in text, or throws IllegalArgumentException. */
  static int parsePort(String text) {
    if (text.isEmpty() || !text.chars().allMatch(c -> c >= '0' && c <= '9')) {
      throw new IllegalArgumentException("not a number: '" + text + "'");
    }
    int port = 0;
    for (int i = 0; i < text.length(); i++) {
      port = port * 10 + (text.charAt(i) - '0');
      if (port > 65535) {
        throw new IllegalArgumentException("out of range: " + text);
      }
    }
    if (port == 0) {
      throw new IllegalArgumentException("out of range: " + text);
    }
    return port;
  }

  /** Returns the port number, or throws ConfigException with the cause. */
  static int readPort(String where, String text) throws ConfigException {
    try {
      return parsePort(text);
    } catch (IllegalArgumentException e) {
      throw new ConfigException(where + ": read port", e);
    }
  }

  /** Joins the message of e and the messages of its causes. */
  static String chain(Throwable e) {
    StringBuilder sb = new StringBuilder(e.getMessage());
    for (Throwable c = e.getCause(); c != null; c = c.getCause()) {
      sb.append(": ").append(c.getMessage());
    }
    return sb.toString();
  }

  /** Returns "port N", or "error: " and the chain of messages. */
  static String checkSetting(String where, String text) {
    try {
      return "port " + readPort(where, text);
    } catch (ConfigException e) {
      return "error: " + chain(e);
    }
  }
}
CheckSettingTest.java 40 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-an-error-with-context/.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class CheckSettingTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("valid", "app.conf:3", "8080", "port 8080"),
        Arguments.of("not-a-number", "app.conf:3", "x", "error: app.conf:3: read port: not a number: 'x'"),
        Arguments.of("too-large", "app.conf:7", "70000", "error: app.conf:7: read port: out of range: 70000"),
        Arguments.of("empty", "app.conf:1", "", "error: app.conf:1: read port: not a number: ''"),
        Arguments.of("zero", "app.conf:2", "0", "error: app.conf:2: read port: out of range: 0"),
        Arguments.of("largest", "app.conf:2", "65535", "port 65535"),
        Arguments.of("leading-space", "app.conf:4", " 80", "error: app.conf:4: read port: not a number: ' 80'"),
        Arguments.of("overflow", "app.conf:5", "99999999999999999999", "error: app.conf:5: read port: out of range: 99999999999999999999"),
        Arguments.of("negative", "app.conf:6", "-1", "error: app.conf:6: read port: not a number: '-1'"));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void checkSetting(String name, String where, String text, String want) {
    assertEquals(want, CheckSetting.checkSetting(where, text), name);
  }

  @Test
  void cause() {
    CheckSetting.ConfigException e =
        assertThrows(CheckSetting.ConfigException.class, () -> CheckSetting.readPort("app.conf:3", "x"));
    assertInstanceOf(IllegalArgumentException.class, e.getCause());
  }
}
check_setting.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-an-error-with-context/.

#include "check_setting.h"

#include <stdio.h>
#include <string.h>

int parse_port(const char *text, int *port, struct setting_error *err) {
    int digits = text[0] != '\0';
    for (const char *p = text; *p != '\0'; p++) {
        if (*p < '0' || *p > '9') {
            digits = 0;
        }
    }
    if (!digits) {
        err->code = SETTING_NOT_A_NUMBER;
        snprintf(err->message, sizeof err->message, "not a number: '%s'", text);
        return err->code;
    }
    long value = 0;
    for (const char *p = text; *p != '\0'; p++) {
        value = value * 10 + (*p - '0');
        if (value > 65535) {
            break;
        }
    }
    if (value == 0 || value > 65535) {
        err->code = SETTING_OUT_OF_RANGE;
        snprintf(err->message, sizeof err->message, "out of range: %s", text);
        return err->code;
    }
    *port = (int)value;
    return 0;
}

int read_port(const char *where, const char *text, int *port, struct setting_error *err) {
    int code = parse_port(text, port, err);
    if (code != 0) {
        char cause[sizeof err->message];
        memcpy(cause, err->message, sizeof cause);
        int n = snprintf(err->message, sizeof err->message, "%s: read port: %s", where, cause);
        if (n >= (int)sizeof err->message) {
            // The message was cut to fit. End it with "..." to show the cut.
            memcpy(err->message + sizeof err->message - 4, "...", 4);
        }
    }
    return code;
}

int check_setting(const char *where, const char *text, char *out, size_t size) {
    int port;
    struct setting_error err;
    if (read_port(where, text, &port, &err) != 0) {
        return snprintf(out, size, "error: %s", err.message);
    }
    return snprintf(out, size, "port %d", port);
}
check_setting.h 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-an-error-with-context/.

#ifndef CHECK_SETTING_H
#define CHECK_SETTING_H

#include <stddef.h>

// The codes of the errors of parse_port.
enum setting_code { SETTING_NOT_A_NUMBER = 1, SETTING_OUT_OF_RANGE = 2 };

// An error has a code and a message. C has no chain of causes, so a wrapper
// puts its context in front of the message and keeps the code.
struct setting_error {
    int code;
    char message[256];
};

// parse_port stores the port number of text in *port and returns 0. On an
// error, it fills *err and returns the code.
int parse_port(const char *text, int *port, struct setting_error *err);

// read_port calls parse_port. On an error, it puts "WHERE: read port: " in
// front of the message, keeps the code, and returns it.
int read_port(const char *where, const char *text, int *port, struct setting_error *err);

// check_setting writes "port N", or "error: " and the message, to out, which
// has room for size bytes. It returns the number of bytes that snprintf wanted.
int check_setting(const char *where, const char *text, char *out, size_t size);

#endif
test_check_setting.c 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-an-error-with-context/.

#include "check_setting.h"

#include <stdio.h>
#include <string.h>

static int failures = 0;

static void check(const char *name, const char *where, const char *text, const char *want) {
    char got[300];
    check_setting(where, text, got, sizeof got);
    if (strcmp(got, want) != 0) {
        fprintf(stderr, "case %s failed: got %s\n", name, got);
        failures++;
    }
}

int main(void) {
    check("valid", "app.conf:3", "8080", "port 8080");
    check("not-a-number", "app.conf:3", "x", "error: app.conf:3: read port: not a number: 'x'");
    check("too-large", "app.conf:7", "70000", "error: app.conf:7: read port: out of range: 70000");
    check("empty", "app.conf:1", "", "error: app.conf:1: read port: not a number: ''");
    check("zero", "app.conf:2", "0", "error: app.conf:2: read port: out of range: 0");
    check("largest", "app.conf:2", "65535", "port 65535");
    check("leading-space", "app.conf:4", " 80", "error: app.conf:4: read port: not a number: ' 80'");
    check("overflow", "app.conf:5", "99999999999999999999", "error: app.conf:5: read port: out of range: 99999999999999999999");
    check("negative", "app.conf:6", "-1", "error: app.conf:6: read port: not a number: '-1'");

    int port;
    struct setting_error err;
    if (read_port("app.conf:3", "x", &port, &err) != SETTING_NOT_A_NUMBER || err.code != SETTING_NOT_A_NUMBER) {
        fprintf(stderr, "case cause failed\n");
        failures++;
    }
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
CheckSetting.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-an-error-with-context/.

using System;
using System.Text;

/// <summary>A setting in a configuration file is bad.</summary>
public sealed class ConfigException : Exception
{
    public ConfigException(string message, Exception inner)
        : base(message, inner)
    {
    }
}

/// <summary>Reads a port setting and wraps the error of the parser with the place of the setting.</summary>
public static class SettingChecker
{
    /// <summary>Returns the port number in text, or throws FormatException.</summary>
    public static int ParsePort(string text)
    {
        foreach (char c in text)
        {
            if (c < '0' || c > '9')
            {
                throw new FormatException($"not a number: '{text}'");
            }
        }
        if (text.Length == 0)
        {
            throw new FormatException($"not a number: '{text}'");
        }
        int port = 0;
        foreach (char c in text)
        {
            port = port * 10 + (c - '0');
            if (port > 65535)
            {
                throw new FormatException($"out of range: {text}");
            }
        }
        if (port == 0)
        {
            throw new FormatException($"out of range: {text}");
        }
        return port;
    }

    /// <summary>Returns the port number, or throws ConfigException with the FormatException as InnerException.</summary>
    public static int ReadPort(string where, string text)
    {
        try
        {
            return ParsePort(text);
        }
        catch (FormatException e)
        {
            throw new ConfigException($"{where}: read port", e);
        }
    }

    /// <summary>Joins the message of e and the messages of its inner exceptions.</summary>
    public static string Chain(Exception e)
    {
        var sb = new StringBuilder(e.Message);
        for (Exception? inner = e.InnerException; inner != null; inner = inner.InnerException)
        {
            sb.Append(": ").Append(inner.Message);
        }
        return sb.ToString();
    }

    /// <summary>Returns "port N", or "error: " and the chain of messages.</summary>
    public static string CheckSetting(string where, string text)
    {
        try
        {
            return $"port {ReadPort(where, text)}";
        }
        catch (ConfigException e)
        {
            return $"error: {Chain(e)}";
        }
    }
}
CheckSettingTests.cs 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-an-error-with-context/.

using System;
using Xunit;

public sealed class CheckSettingTests
{
    public static TheoryData<string, string, string, string> Cases => new()
    {
        { "valid", "app.conf:3", "8080", "port 8080" },
        { "not-a-number", "app.conf:3", "x", "error: app.conf:3: read port: not a number: 'x'" },
        { "too-large", "app.conf:7", "70000", "error: app.conf:7: read port: out of range: 70000" },
        { "empty", "app.conf:1", "", "error: app.conf:1: read port: not a number: ''" },
        { "zero", "app.conf:2", "0", "error: app.conf:2: read port: out of range: 0" },
        { "largest", "app.conf:2", "65535", "port 65535" },
        { "leading-space", "app.conf:4", " 80", "error: app.conf:4: read port: not a number: ' 80'" },
        { "overflow", "app.conf:5", "99999999999999999999", "error: app.conf:5: read port: out of range: 99999999999999999999" },
        { "negative", "app.conf:6", "-1", "error: app.conf:6: read port: not a number: '-1'" },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Check(string name, string where, string text, string want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, SettingChecker.CheckSetting(where, text));
    }

    [Fact]
    public void Cause()
    {
        var e = Assert.Throws<ConfigException>(() => SettingChecker.ReadPort("app.conf:3", "x"));
        Assert.IsType<FormatException>(e.InnerException);
    }
}
checkSetting.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-an-error-with-context/.

/**
 * Returns the port number in text, or throws an Error.
 * @param {string} text
 * @returns {number}
 */
export function parsePort(text) {
  if (!/^[0-9]+$/.test(text)) {
    throw new Error(`not a number: '${text}'`);
  }
  const port = Number(text);
  if (port < 1 || port > 65535) {
    throw new Error(`out of range: ${text}`);
  }
  return port;
}

/**
 * Returns the port number, or throws an Error whose cause is the error of parsePort.
 * @param {string} where
 * @param {string} text
 * @returns {number}
 */
export function readPort(where, text) {
  try {
    return parsePort(text);
  } catch (e) {
    throw new Error(`${where}: read port`, { cause: e });
  }
}

/**
 * Joins the message of e and the messages of its causes.
 * @param {unknown} e
 * @returns {string}
 */
function chain(e) {
  const parts = [];
  let cur = e;
  while (cur instanceof Error) {
    parts.push(cur.message);
    cur = cur.cause;
  }
  return parts.join(": ");
}

/**
 * Returns "port N", or "error: " and the chain of messages.
 * @param {string} where
 * @param {string} text
 * @returns {string}
 */
export function checkSetting(where, text) {
  try {
    return `port ${readPort(where, text)}`;
  } catch (e) {
    return `error: ${chain(e)}`;
  }
}
checkSetting.test.js 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-an-error-with-context/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { checkSetting, readPort } from "./checkSetting.js";

const cases = [
  ["valid", "app.conf:3", "8080", "port 8080"],
  ["not-a-number", "app.conf:3", "x", "error: app.conf:3: read port: not a number: 'x'"],
  ["too-large", "app.conf:7", "70000", "error: app.conf:7: read port: out of range: 70000"],
  ["empty", "app.conf:1", "", "error: app.conf:1: read port: not a number: ''"],
  ["zero", "app.conf:2", "0", "error: app.conf:2: read port: out of range: 0"],
  ["largest", "app.conf:2", "65535", "port 65535"],
  ["leading-space", "app.conf:4", " 80", "error: app.conf:4: read port: not a number: ' 80'"],
  ["overflow", "app.conf:5", "99999999999999999999", "error: app.conf:5: read port: out of range: 99999999999999999999"],
  ["negative", "app.conf:6", "-1", "error: app.conf:6: read port: not a number: '-1'"],
];

for (const [name, where, text, want] of cases) {
  test(name, () => {
    assert.equal(checkSetting(where, text), want);
  });
}

test("cause", () => {
  assert.throws(
    () => readPort("app.conf:3", "x"),
    (e) => e instanceof Error && e.cause instanceof Error && e.cause.message === "not a number: 'x'",
  );
});
checkSetting.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-an-error-with-context/.

/** Returns the port number in text, or throws an Error. */
export function parsePort(text: string): number {
  if (!/^[0-9]+$/.test(text)) {
    throw new Error(`not a number: '${text}'`);
  }
  const port = Number(text);
  if (port < 1 || port > 65535) {
    throw new Error(`out of range: ${text}`);
  }
  return port;
}

/** Returns the port number, or throws an Error whose cause is the error of parsePort. */
export function readPort(where: string, text: string): number {
  try {
    return parsePort(text);
  } catch (e) {
    throw new Error(`${where}: read port`, { cause: e });
  }
}

/** Joins the message of e and the messages of its causes. */
function chain(e: unknown): string {
  const parts: string[] = [];
  let cur = e;
  while (cur instanceof Error) {
    parts.push(cur.message);
    cur = cur.cause;
  }
  return parts.join(": ");
}

/** Returns "port N", or "error: " and the chain of messages. */
export function checkSetting(where: string, text: string): string {
  try {
    return `port ${readPort(where, text)}`;
  } catch (e) {
    return `error: ${chain(e)}`;
  }
}
checkSetting.test.ts 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-an-error-with-context/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { checkSetting, readPort } from "./checkSetting.ts";

const cases: [string, string, string, string][] = [
  ["valid", "app.conf:3", "8080", "port 8080"],
  ["not-a-number", "app.conf:3", "x", "error: app.conf:3: read port: not a number: 'x'"],
  ["too-large", "app.conf:7", "70000", "error: app.conf:7: read port: out of range: 70000"],
  ["empty", "app.conf:1", "", "error: app.conf:1: read port: not a number: ''"],
  ["zero", "app.conf:2", "0", "error: app.conf:2: read port: out of range: 0"],
  ["largest", "app.conf:2", "65535", "port 65535"],
  ["leading-space", "app.conf:4", " 80", "error: app.conf:4: read port: not a number: ' 80'"],
  ["overflow", "app.conf:5", "99999999999999999999", "error: app.conf:5: read port: out of range: 99999999999999999999"],
  ["negative", "app.conf:6", "-1", "error: app.conf:6: read port: not a number: '-1'"],
];

for (const [name, where, text, want] of cases) {
  test(name, () => {
    assert.equal(checkSetting(where, text), want);
  });
}

test("cause", () => {
  assert.throws(
    () => readPort("app.conf:3", "x"),
    (e: unknown) => e instanceof Error && e.cause instanceof Error && e.cause.message === "not a number: 'x'",
  );
});
check_setting.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-an-error-with-context/.

// Package setting reads a port setting and wraps the error of the parser
// with the place of the setting.
package setting

import (
	"errors"
	"fmt"
)

// The errors of ParsePort wrap one of these two values.
var (
	ErrNotANumber = errors.New("not a number")
	ErrOutOfRange = errors.New("out of range")
)

// ParsePort returns the port number in text.
func ParsePort(text string) (int, error) {
	for _, c := range text {
		if c < '0' || c > '9' {
			return 0, fmt.Errorf("%w: '%s'", ErrNotANumber, text)
		}
	}
	if text == "" {
		return 0, fmt.Errorf("%w: '%s'", ErrNotANumber, text)
	}
	port := 0
	for _, c := range text {
		port = port*10 + int(c-'0')
		if port > 65535 {
			return 0, fmt.Errorf("%w: %s", ErrOutOfRange, text)
		}
	}
	if port == 0 {
		return 0, fmt.Errorf("%w: %s", ErrOutOfRange, text)
	}
	return port, nil
}

// ReadPort returns the port number. On an error, it adds where to the
// message, and %w keeps the error of ParsePort for errors.Is and errors.As.
func ReadPort(where, text string) (int, error) {
	port, err := ParsePort(text)
	if err != nil {
		return 0, fmt.Errorf("%s: read port: %w", where, err)
	}
	return port, nil
}

// CheckSetting returns "port N", or "error: " and the message. The message
// of an error from fmt.Errorf already has the message of the wrapped error.
func CheckSetting(where, text string) string {
	port, err := ReadPort(where, text)
	if err != nil {
		return "error: " + err.Error()
	}
	return fmt.Sprintf("port %d", port)
}
check_setting_test.go 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-an-error-with-context/.

package setting

import (
	"errors"
	"testing"
)

var cases = []struct {
	name, where, text, want string
}{
	{"valid", "app.conf:3", "8080", "port 8080"},
	{"not-a-number", "app.conf:3", "x", "error: app.conf:3: read port: not a number: 'x'"},
	{"too-large", "app.conf:7", "70000", "error: app.conf:7: read port: out of range: 70000"},
	{"empty", "app.conf:1", "", "error: app.conf:1: read port: not a number: ''"},
	{"zero", "app.conf:2", "0", "error: app.conf:2: read port: out of range: 0"},
	{"largest", "app.conf:2", "65535", "port 65535"},
	{"leading-space", "app.conf:4", " 80", "error: app.conf:4: read port: not a number: ' 80'"},
	{"overflow", "app.conf:5", "99999999999999999999", "error: app.conf:5: read port: out of range: 99999999999999999999"},
	{"negative", "app.conf:6", "-1", "error: app.conf:6: read port: not a number: '-1'"},
}

func TestCheckSetting(t *testing.T) {
	for _, c := range cases {
		if got := CheckSetting(c.where, c.text); got != c.want {
			t.Errorf("%s: got %q, want %q", c.name, got, c.want)
		}
	}
}

func TestCause(t *testing.T) {
	_, err := ReadPort("app.conf:3", "x")
	if !errors.Is(err, ErrNotANumber) {
		t.Errorf("errors.Is(%v, ErrNotANumber) is false", err)
	}
}
check_setting.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-an-error-with-context/.

use std::error::Error;
use std::fmt;

/// The error of parse_port.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParseError {
    NotANumber(String),
    OutOfRange(String),
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ParseError::NotANumber(text) => write!(f, "not a number: '{text}'"),
            ParseError::OutOfRange(text) => write!(f, "out of range: {text}"),
        }
    }
}

impl Error for ParseError {}

/// A setting is bad. The cause is the error of parse_port.
#[derive(Debug)]
pub struct ConfigError {
    pub context: String,
    pub cause: ParseError,
}

// Display shows only the context. The cause comes from source(), so that a
// program that prints the chain does not print the cause two times.
impl fmt::Display for ConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.context)
    }
}

impl Error for ConfigError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(&self.cause)
    }
}

/// Returns the port number in text.
pub fn parse_port(text: &str) -> Result<u16, ParseError> {
    if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) {
        return Err(ParseError::NotANumber(text.to_string()));
    }
    let mut port: u32 = 0;
    for b in text.bytes() {
        port = port * 10 + u32::from(b - b'0');
        if port > 65535 {
            return Err(ParseError::OutOfRange(text.to_string()));
        }
    }
    if port == 0 {
        return Err(ParseError::OutOfRange(text.to_string()));
    }
    Ok(port as u16)
}

/// Returns the port number, or a ConfigError that keeps the ParseError.
pub fn read_port(place: &str, text: &str) -> Result<u16, ConfigError> {
    parse_port(text).map_err(|cause| ConfigError {
        context: format!("{place}: read port"),
        cause,
    })
}

/// Joins the message of e and the messages of its sources.
fn chain(e: &dyn Error) -> String {
    let mut message = e.to_string();
    let mut cur = e.source();
    while let Some(s) = cur {
        message.push_str(": ");
        message.push_str(&s.to_string());
        cur = s.source();
    }
    message
}

/// Returns "port N", or "error: " and the chain of messages.
pub fn check_setting(place: &str, text: &str) -> String {
    match read_port(place, text) {
        Ok(port) => format!("port {port}"),
        Err(e) => format!("error: {}", chain(&e)),
    }
}
tests/check_setting_test.rs 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-an-error-with-context/.

use algo_wrap_an_error_with_context::{check_setting, read_port, ParseError};

#[test]
fn cases() {
    let cases: &[(&str, &str, &str, &str)] = &[
        ("valid", "app.conf:3", "8080", "port 8080"),
        ("not-a-number", "app.conf:3", "x", "error: app.conf:3: read port: not a number: 'x'"),
        ("too-large", "app.conf:7", "70000", "error: app.conf:7: read port: out of range: 70000"),
        ("empty", "app.conf:1", "", "error: app.conf:1: read port: not a number: ''"),
        ("zero", "app.conf:2", "0", "error: app.conf:2: read port: out of range: 0"),
        ("largest", "app.conf:2", "65535", "port 65535"),
        ("leading-space", "app.conf:4", " 80", "error: app.conf:4: read port: not a number: ' 80'"),
        ("overflow", "app.conf:5", "99999999999999999999", "error: app.conf:5: read port: out of range: 99999999999999999999"),
        ("negative", "app.conf:6", "-1", "error: app.conf:6: read port: not a number: '-1'"),
    ];
    for &(name, place, text, want) in cases {
        assert_eq!(check_setting(place, text), want, "{name}");
    }
}

#[test]
fn cause() {
    let e = read_port("app.conf:3", "x").unwrap_err();
    assert_eq!(e.cause, ParseError::NotANumber("x".to_string()));
}
check_setting.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/wrap-an-error-with-context/.

# Bash has no error values. Each function returns a status and puts the
# message in the global variable ERROR_MESSAGE. Call the functions without
# $( ), because a command substitution runs in a subshell.

# parse_port TEXT
# Sets PORT and returns 0, or sets ERROR_MESSAGE and returns 1 or 2.
parse_port() {
  local text=$1 value=0 i
  if [[ ! $text =~ ^[0-9]+$ ]]; then
    ERROR_MESSAGE="not a number: '$text'"
    return 1
  fi
  for ((i = 0; i < ${#text}; i++)); do
    value=$((value * 10 + ${text:i:1}))
    if ((value > 65535)); then
      break
    fi
  done
  if ((value == 0 || value > 65535)); then
    ERROR_MESSAGE="out of range: $text"
    return 2
  fi
  PORT=$value
}

# read_port WHERE TEXT
# Like parse_port, but puts "WHERE: read port: " in front of the message and
# keeps the status of parse_port.
read_port() {
  local status
  parse_port "$2" && return 0
  status=$?
  ERROR_MESSAGE="$1: read port: $ERROR_MESSAGE"
  return "$status"
}

# check_setting WHERE TEXT
# Prints "port N", or "error: " and the message.
check_setting() {
  if read_port "$1" "$2"; then
    echo "port $PORT"
  else
    echo "error: $ERROR_MESSAGE"
  fi
}
test_check_setting.bats 29 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/wrap-an-error-with-context/.

setup() {
  source "$BATS_TEST_DIRNAME/check_setting.sh"
}

check() { # check WHERE TEXT WANT
  local got
  got=$(check_setting "$1" "$2")
  [ "$got" = "$3" ] || { printf 'got:  %s\nwant: %s\n' "$got" "$3"; return 1; }
}

@test "valid" { check "app.conf:3" "8080" "port 8080"; }
@test "not-a-number" { check "app.conf:3" "x" "error: app.conf:3: read port: not a number: 'x'"; }
@test "too-large" { check "app.conf:7" "70000" "error: app.conf:7: read port: out of range: 70000"; }
@test "empty" { check "app.conf:1" "" "error: app.conf:1: read port: not a number: ''"; }
@test "zero" { check "app.conf:2" "0" "error: app.conf:2: read port: out of range: 0"; }
@test "largest" { check "app.conf:2" "65535" "port 65535"; }
@test "leading-space" { check "app.conf:4" " 80" "error: app.conf:4: read port: not a number: ' 80'"; }
@test "overflow" { check "app.conf:5" "99999999999999999999" "error: app.conf:5: read port: out of range: 99999999999999999999"; }
@test "negative" { check "app.conf:6" "-1" "error: app.conf:6: read port: not a number: '-1'"; }

@test "cause" {
  local status=0
  read_port app.conf:3 x || status=$?
  [ "$status" -eq 1 ]
}

References

  1. Errors and Exceptions, The Python Tutorial, 8.5 Exception Chaining
  2. Built-in Exceptions, The Python Standard Library, Exception context
  3. Error: cause, MDN Web Docs, the introduction
  4. Chained Exceptions, The Java Tutorials, the first paragraphs
  5. Exception.InnerException Property, .NET API, Remarks
  6. std::throw_with_nested, cppreference.com, the description
  7. std::rethrow_if_nested, cppreference.com, the description
  8. Damien Neil and Jonathan Amsterdam, Working with Errors in Go 1.13, The Go Blog, 17 October 2019, Wrapping errors with %w; Whether to Wrap
  9. std::error::Error, Rust standard library, Error source
  10. anyhow, docs.rs, the crate description, Context
  11. Command Execution Environment, Bash Reference Manual, the subshell paragraph

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)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source