Taskcore
Define a custom error type
Also called custom exception, user-defined exception, custom error class, error struct, error enum, exception subclass.
Report a bad port number with an error type of your own that keeps the text and the reason as fields, and let the caller pick out that type from the other errors.
- Evidence
- Code in 10 languages
Task
Define an error type for one kind of failure, give it fields that describe the failure, and let the caller pick out that type. The function parse_port(text) reads a TCP port number. When the text is bad, it reports a PortError with two fields:
text: the text that failed,reason:"empty","not a number"or"out of range".
The text is good when it has only the ASCII digits 0 to 9, and its value is from 1 to 65535. The function check_port(text) calls parse_port. It returns "port N" on success. On a PortError, it returns the message of the error, "invalid port 'TEXT': REASON". For example, check_port("8080") is "port 8080" and check_port("x80") is "invalid port 'x80': not a number".
A general error, such as a string or a plain Exception, has only a message. A program that must act on the reason must then read the message. A custom type gives the reason to the program as a field, and its name tells the handler which errors to take. Error explains what an error is. Exception and Error value are the two ways to report one. The type in this task works with both.
Solutions
| Language | The error type | How the caller picks out the type |
|---|---|---|
| Python | class PortError(Exception) |
except PortError as e: |
| JavaScript, TypeScript | class PortError extends Error |
e instanceof PortError |
| Java | class PortException extends Exception |
catch (PortException e) |
| C# | class PortException : Exception |
catch (PortException e) |
| C++ | class PortError : public std::runtime_error |
catch (const PortError &e) |
| Go | type PortError struct with an Error method |
errors.As(err, &pe) |
| Rust | struct PortError that implements Error |
match on the Result |
| C | struct port_error and enum port_reason |
the return value -1 |
| Bash | two global variables and the exit status | if parse_port "$1" |
- Python. "Exceptions should typically be derived from the Exception class, either directly or indirectly"1. The tutorial adds that such classes "are usually kept simple, often only offering a number of attributes that allow information about the error to be extracted by handlers for the exception"1.
PortErrorpasses the message toException.__init__and keepstextandreasonas attributes. Most exception names end in "Error"1, so the solution usesPortError. - JavaScript and TypeScript. MDN gives the reason for a subclass: you can "define your own error types deriving from Error to be able to throw new MyError() and use instanceof MyError to check the kind of error in the exception handler"2. The
catchclause of the solution tests the type withinstanceofand throws other errors again. The constructor also setsthis.name, as the MDN example does2. The TypeScript solution is the same code with types on the fields. - Java. The tutorial names the parent: "the parent class of LinkedListException should be Exception"3, and it says that "it's good practice to append the string Exception to the names of all classes that inherit (directly or indirectly) from the Exception class"3. So the type is
PortException. A subclass ofExceptionthat is not a subclass ofRuntimeExceptionis a checked exception, and "Checked exceptions need to be declared in a method or constructor's throws clause"4. SoparsePorthasthrows PortException. - C#. The .NET guide says: "When a custom exception is necessary, name it appropriately and derive it from the Exception class"5. It asks for more properties "only when there's a programmatic scenario where the additional information is useful"5. Here the caller can act on
Reason, so the type has the propertiesTextandReason. The guide also tells you to "implement the three common constructors"6. This short solution has only the constructor that it uses. - C++. The solution derives from
std::runtime_error, which "reports errors that are due to events beyond the scope of the program and cannot be easily predicted"7. Bad input from a user is such an event. The constructor ofruntime_error"Constructs the exception object with what_arg as explanatory string"7, sowhat()gives the message. The handler catches by reference toconst. - Go. "The error type is an interface type. An error variable represents any value that can describe itself as a string"8. So a struct with an
Error() stringmethod is an error. The Go blog shows the same pattern withjson.SyntaxError, whose fieldOffset"isn’t even shown in the default formatting of the error, but callers can use it"8. The caller gets the struct back witherrors.As, which "finds the first error in err's tree that matches target, and if one is found, sets target to that error value and returns true"9. The documentation says "For most uses, prefer AsType"9. "As is equivalent to AsType but sets its target argument rather than returning the matching error"9, so either one works here. - Rust. "Errors must describe themselves through the Display and Debug traits"10. The solution derives
Debug, writesDisplayby hand, and adds an emptyimpl Error. The reason is an enum, so amatchon it must cover each reason. The standard library also says that error messages "are typically concise lowercase sentences without trailing punctuation"10, and the messages of the solution follow that rule. The crate thiserror "provides a convenient derive macro for the standard library’s std::error::Error trait"11, so a larger program can put anerrorattribute with the message on each variant in place of theDisplaycode. "Thiserror deliberately does not appear in your public API"11. - C. The solution has no exceptions.
parse_portreturns-1and fills astruct port_errorthat the caller passes in. The reason is anenum, andport_reason_nameturns it into text. Error codes explains this style. - Bash. A function can report only an exit status, and "a non-zero exit status indicates failure"12. So
parse_portreturns 1 and puts the fields in the global variablesPORT_ERROR_TEXTandPORT_ERROR_REASON. The caller must not call it in$( ). Command substitution runs in a subshell, and a command in a subshell "cannot affect the shell’s execution environment"13. The variables would be lost.
The fields at work
The handler can act on the reason without reading the message. Here only an "out of range" error gets a hint:
class PortError(Exception):
def __init__(self, text, reason):
super().__init__(f"invalid port '{text}': {reason}")
self.text = text
self.reason = reason
def parse_port(text):
if text == "":
raise PortError(text, "empty")
if any(c not in "0123456789" for c in text):
raise PortError(text, "not a number")
port = int(text)
if not 1 <= port <= 65535:
raise PortError(text, "out of range")
return port
for text in ["8080", "x80", "70000"]:
try:
print("port", parse_port(text))
except PortError as e:
print(e)
if e.reason == "out of range":
print(" hint: use a port from 1 to 65535")
port 8080
invalid port 'x80': not a number
invalid port '70000': out of range
hint: use a port from 1 to 65535
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
empty: the empty text has its own reason,"empty", so that the message does not say that nothing is "not a number".zeroandone: 0 has only digits, but the task takes ports from 1 to 65535, so the reason is"out of range". 1 is the smallest port.largestandtoo-large: 65535 is the largest port, and 65536 is out of range.overflow: twenty digits do not fit in a 64-bit integer. The solutions stop when the value goes above 65535, so the reason is"out of range", not an overflow.leading-zeros:"0080"has only digits, and its value is 80.negativeandleading-space: a sign or a space is not a digit, so the reason is"not a number". The solutions test each character before they compute the value.
Pitfalls
- The wrong base class. In Python,
KeyboardInterrupt"inherits from BaseException so as to not be accidentally caught by code that catches Exception"14. The same rule applies to each subclass ofBaseException. The documentation tells programmers "to derive new exceptions from the Exception class or one of its subclasses, and not from BaseException"14. A handler forExceptiondoes not catch an error that derives fromBaseException:
This code runs but gives a wrong answer on purpose.
class PortError(BaseException):
pass
try:
try:
raise PortError("invalid port 'x80': not a number")
except Exception:
print("handled")
except BaseException as e:
print("not handled by except Exception:", type(e).__name__)
not handled by except Exception: PortError
- No name in JavaScript. For
Error.prototype.name, "the initial value is "Error""2. A subclass that does not setnameprints as a plainError:
This code runs but gives a wrong answer on purpose.
class PortError extends Error {}
const e = new PortError("invalid port 'x80': not a number");
console.log(String(e));
console.log(e instanceof PortError);
Error: invalid port 'x80': not a number
true
The type is right, but a log shows only Error. Set this.name = "PortError" in the constructor.
- A nil pointer in an error. In Go, an interface value holds a type and a value. The FAQ says that "if any concrete value has been stored in the interface, the interface will not be nil"15. A function that returns a
*PortErrorvariable as anerrorreturns a non-nil error even when the pointer is nil:
This code runs but gives a wrong answer on purpose.
package main
import "fmt"
type PortError struct{ Text, Reason string }
func (e *PortError) Error() string {
return "invalid port '" + e.Text + "': " + e.Reason
}
func parsePort(text string) (int, error) {
var perr *PortError // stays nil when the text is good
if text == "" {
perr = &PortError{text, "empty"}
}
return 80, perr
}
func main() {
_, err := parsePort("80")
fmt.Println("err != nil:", err != nil)
}
err != nil: true
The FAQ gives the fix: "To return a proper nil error to the caller, the function must return an explicit nil"15. The Go solution returns nil on success, and the result type of ParsePort is error, not *PortError.
- A test on the message. A handler that compares the message, such as
if "out of range" in str(e), breaks when someone changes the words of the message. Test the type and the fields. Keep the message for people.
Related tasks
- Wrap an error with context: add context to an error, and keep the error as its cause.
- Log an error: write an error to the log with its fields.
- Pattern match on a value: a
matchon an enum with data, such as the reason in the Rust solution.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/define-a-custom-error-type/.
class PortError(Exception):
"""The text is not a valid TCP port number."""
def __init__(self, text: str, reason: str) -> None:
super().__init__(f"invalid port '{text}': {reason}")
self.text = text
self.reason = reason
def parse_port(text: str) -> int:
"""Return the port number in text, or raise PortError."""
if text == "":
raise PortError(text, "empty")
if any(c not in "0123456789" for c in text):
raise PortError(text, "not a number")
port = int(text)
if not 1 <= port <= 65535:
raise PortError(text, "out of range")
return port
def check_port(text: str) -> str:
"""Return "port N", or the message of the PortError."""
try:
return f"port {parse_port(text)}"
except PortError as e:
# Only a PortError comes here. A bug, such as a TypeError, goes on up.
return str(e)
test_check_port.py 33 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/define-a-custom-error-type/.
import pytest
from check_port import PortError, check_port, parse_port
CASES = {
"valid": ("8080", "port 8080"),
"not-a-number": ("x80", "invalid port 'x80': not a number"),
"too-large": ("65536", "invalid port '65536': out of range"),
"empty": ("", "invalid port '': empty"),
"zero": ("0", "invalid port '0': out of range"),
"one": ("1", "port 1"),
"largest": ("65535", "port 65535"),
"leading-zeros": ("0080", "port 80"),
"negative": ("-1", "invalid port '-1': not a number"),
"leading-space": (" 80", "invalid port ' 80': not a number"),
"overflow": ("99999999999999999999", "invalid port '99999999999999999999': out of range"),
}
@pytest.mark.parametrize("name", CASES)
def test_check_port(name):
text, want = CASES[name]
assert check_port(text) == want
def test_fields():
with pytest.raises(PortError) as info:
parse_port("x80")
assert info.value.text == "x80"
assert info.value.reason == "not a number"
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-custom-error-type/.
#include "check_port.hpp"
#include <algorithm>
#include <utility>
PortError::PortError(std::string text, std::string reason)
: std::runtime_error("invalid port '" + text + "': " + reason),
text_(std::move(text)),
reason_(std::move(reason)) {}
int parse_port(const std::string &text) {
if (text.empty()) {
throw PortError(text, "empty");
}
if (!std::all_of(text.begin(), text.end(), [](char c) { return c >= '0' && c <= '9'; })) {
throw PortError(text, "not a number");
}
long value = 0;
for (char c : text) {
value = value * 10 + (c - '0');
if (value > 65535) {
throw PortError(text, "out of range");
}
}
if (value == 0) {
throw PortError(text, "out of range");
}
return static_cast<int>(value);
}
std::string check_port(const std::string &text) {
try {
int port = parse_port(text);
return "port " + std::to_string(port);
} catch (const PortError &e) {
// Catch by reference to const, so the object is not sliced or copied.
return e.what();
}
}
check_port.hpp 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-custom-error-type/.
#pragma once
#include <stdexcept>
#include <string>
// PortError reports that a text is not a valid TCP port number.
class PortError : public std::runtime_error {
public:
PortError(std::string text, std::string reason);
const std::string &text() const noexcept { return text_; }
const std::string &reason() const noexcept { return reason_; }
private:
std::string text_;
std::string reason_;
};
// parse_port returns the port number in text, or throws PortError.
int parse_port(const std::string &text);
// check_port returns "port N", or the message of the PortError.
std::string check_port(const std::string &text);
test_check_port.cpp 48 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-custom-error-type/.
#include "check_port.hpp"
#include <iostream>
#include <string>
#include <string_view>
static int failures = 0;
static void check(std::string_view name, const std::string &text, const std::string &want) {
std::string got = check_port(text);
if (got != want) {
std::cerr << "case " << name << " failed: got " << got << "\n";
failures++;
}
}
int main() {
check("valid", "8080", "port 8080");
check("not-a-number", "x80", "invalid port 'x80': not a number");
check("too-large", "65536", "invalid port '65536': out of range");
check("empty", "", "invalid port '': empty");
check("zero", "0", "invalid port '0': out of range");
check("one", "1", "port 1");
check("largest", "65535", "port 65535");
check("leading-zeros", "0080", "port 80");
check("negative", "-1", "invalid port '-1': not a number");
check("leading-space", " 80", "invalid port ' 80': not a number");
check("overflow", "99999999999999999999", "invalid port '99999999999999999999': out of range");
try {
parse_port("x80");
std::cerr << "case fields failed: no exception\n";
failures++;
} catch (const PortError &e) {
if (e.text() != "x80" || e.reason() != "not a number") {
std::cerr << "case fields failed\n";
failures++;
}
}
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-custom-error-type/.
/** Reads a TCP port number and reports a bad one with its own exception type. */
final class CheckPort {
private CheckPort() {}
/** Reports that a text is not a valid TCP port number. */
static final class PortException extends Exception {
// Exception is Serializable, and javac -Xlint:serial asks for this field.
private static final long serialVersionUID = 1L;
private final String text;
private final String reason;
PortException(String text, String reason) {
super("invalid port '" + text + "': " + reason);
this.text = text;
this.reason = reason;
}
String text() {
return text;
}
String reason() {
return reason;
}
}
/** Returns the port number in text. PortException is checked, so it is in the throws clause. */
static int parsePort(String text) throws PortException {
if (text.isEmpty()) {
throw new PortException(text, "empty");
}
if (!text.chars().allMatch(c -> c >= '0' && c <= '9')) {
throw new PortException(text, "not a number");
}
int port = 0;
for (int i = 0; i < text.length(); i++) {
port = port * 10 + (text.charAt(i) - '0');
if (port > 65535) {
throw new PortException(text, "out of range");
}
}
if (port == 0) {
throw new PortException(text, "out of range");
}
return port;
}
/** Returns "port N", or the message of the PortException. */
static String checkPort(String text) {
try {
return "port " + parsePort(text);
} catch (PortException e) {
return e.getMessage();
}
}
}
CheckPortTest.java 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-custom-error-type/.
import static org.junit.jupiter.api.Assertions.assertEquals;
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 CheckPortTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("valid", "8080", "port 8080"),
Arguments.of("not-a-number", "x80", "invalid port 'x80': not a number"),
Arguments.of("too-large", "65536", "invalid port '65536': out of range"),
Arguments.of("empty", "", "invalid port '': empty"),
Arguments.of("zero", "0", "invalid port '0': out of range"),
Arguments.of("one", "1", "port 1"),
Arguments.of("largest", "65535", "port 65535"),
Arguments.of("leading-zeros", "0080", "port 80"),
Arguments.of("negative", "-1", "invalid port '-1': not a number"),
Arguments.of("leading-space", " 80", "invalid port ' 80': not a number"),
Arguments.of("overflow", "99999999999999999999", "invalid port '99999999999999999999': out of range"));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void checkPort(String name, String text, String want) {
assertEquals(want, CheckPort.checkPort(text), name);
}
@Test
void fields() {
CheckPort.PortException e =
assertThrows(CheckPort.PortException.class, () -> CheckPort.parsePort("x80"));
assertEquals("x80", e.text());
assertEquals("not a number", e.reason());
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-custom-error-type/.
#include "check_port.h"
#include <stdio.h>
const char *port_reason_name(enum port_reason reason) {
switch (reason) {
case PORT_EMPTY:
return "empty";
case PORT_NOT_A_NUMBER:
return "not a number";
case PORT_OUT_OF_RANGE:
return "out of range";
}
return "unknown";
}
static int fail(struct port_error *err, const char *text, enum port_reason reason) {
err->text = text;
err->reason = reason;
return -1;
}
int parse_port(const char *text, int *port, struct port_error *err) {
if (text[0] == '\0') {
return fail(err, text, PORT_EMPTY);
}
for (const char *p = text; *p != '\0'; p++) {
if (*p < '0' || *p > '9') {
return fail(err, text, PORT_NOT_A_NUMBER);
}
}
long value = 0;
for (const char *p = text; *p != '\0'; p++) {
value = value * 10 + (*p - '0');
if (value > 65535) {
return fail(err, text, PORT_OUT_OF_RANGE);
}
}
if (value == 0) {
return fail(err, text, PORT_OUT_OF_RANGE);
}
*port = (int)value;
return 0;
}
int check_port(const char *text, char *out, size_t size) {
int port;
struct port_error err;
if (parse_port(text, &port, &err) != 0) {
return snprintf(out, size, "invalid port '%s': %s", err.text, port_reason_name(err.reason));
}
return snprintf(out, size, "port %d", port);
}
check_port.h 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-custom-error-type/.
#ifndef CHECK_PORT_H
#define CHECK_PORT_H
#include <stddef.h>
// Why a text is not a valid TCP port number.
enum port_reason { PORT_EMPTY, PORT_NOT_A_NUMBER, PORT_OUT_OF_RANGE };
// C has no exception types, so the error is a struct that the caller passes in.
struct port_error {
const char *text; // the text that failed; it points into the caller's string
enum port_reason reason;
};
// port_reason_name returns the reason as a string literal, such as "empty".
const char *port_reason_name(enum port_reason reason);
// parse_port stores the port number of text in *port and returns 0. On an
// error it fills *err and returns -1.
int parse_port(const char *text, int *port, struct port_error *err);
// check_port writes "port N", or the message of the error, to out, which has
// room for size bytes. It returns the number of bytes that snprintf wanted.
int check_port(const char *text, char *out, size_t size);
#endif
test_check_port.c 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-custom-error-type/.
#include "check_port.h"
#include <stdio.h>
#include <string.h>
static int failures = 0;
static void check(const char *name, const char *text, const char *want) {
char got[128];
check_port(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", "8080", "port 8080");
check("not-a-number", "x80", "invalid port 'x80': not a number");
check("too-large", "65536", "invalid port '65536': out of range");
check("empty", "", "invalid port '': empty");
check("zero", "0", "invalid port '0': out of range");
check("one", "1", "port 1");
check("largest", "65535", "port 65535");
check("leading-zeros", "0080", "port 80");
check("negative", "-1", "invalid port '-1': not a number");
check("leading-space", " 80", "invalid port ' 80': not a number");
check("overflow", "99999999999999999999", "invalid port '99999999999999999999': out of range");
int port;
struct port_error err;
if (parse_port("x80", &port, &err) != -1 || strcmp(err.text, "x80") != 0 || err.reason != PORT_NOT_A_NUMBER) {
fprintf(stderr, "case fields failed\n");
failures++;
}
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-custom-error-type/.
using System;
/// <summary>Reports that a text is not a valid TCP port number.</summary>
public sealed class PortException : Exception
{
public PortException(string text, string reason)
: base($"invalid port '{text}': {reason}")
{
Text = text;
Reason = reason;
}
public string Text { get; }
public string Reason { get; }
}
/// <summary>Reads a TCP port number and reports a bad one with PortException.</summary>
public static class PortChecker
{
/// <summary>Returns the port number in text, or throws PortException.</summary>
public static int ParsePort(string text)
{
if (text.Length == 0)
{
throw new PortException(text, "empty");
}
foreach (char c in text)
{
if (c < '0' || c > '9')
{
throw new PortException(text, "not a number");
}
}
int port = 0;
foreach (char c in text)
{
port = port * 10 + (c - '0');
if (port > 65535)
{
throw new PortException(text, "out of range");
}
}
if (port == 0)
{
throw new PortException(text, "out of range");
}
return port;
}
/// <summary>Returns "port N", or the message of the PortException.</summary>
public static string CheckPort(string text)
{
try
{
return $"port {ParsePort(text)}";
}
catch (PortException e)
{
return e.Message;
}
}
}
CheckPortTests.cs 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-custom-error-type/.
using Xunit;
public sealed class CheckPortTests
{
public static TheoryData<string, string, string> Cases => new()
{
{ "valid", "8080", "port 8080" },
{ "not-a-number", "x80", "invalid port 'x80': not a number" },
{ "too-large", "65536", "invalid port '65536': out of range" },
{ "empty", "", "invalid port '': empty" },
{ "zero", "0", "invalid port '0': out of range" },
{ "one", "1", "port 1" },
{ "largest", "65535", "port 65535" },
{ "leading-zeros", "0080", "port 80" },
{ "negative", "-1", "invalid port '-1': not a number" },
{ "leading-space", " 80", "invalid port ' 80': not a number" },
{ "overflow", "99999999999999999999", "invalid port '99999999999999999999': out of range" },
};
[Theory]
[MemberData(nameof(Cases))]
public void Check(string name, string text, string want)
{
Assert.NotNull(name);
Assert.Equal(want, PortChecker.CheckPort(text));
}
[Fact]
public void Fields()
{
var e = Assert.Throws<PortException>(() => PortChecker.ParsePort("x80"));
Assert.Equal("x80", e.Text);
Assert.Equal("not a number", e.Reason);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-custom-error-type/.
/** The text is not a valid TCP port number. */
export class PortError extends Error {
constructor(text, reason) {
super(`invalid port '${text}': ${reason}`);
// Without this line, the name is "Error" in messages and stack traces.
this.name = "PortError";
this.text = text;
this.reason = reason;
}
}
/**
* Returns the port number in text, or throws a PortError.
* @param {string} text
* @returns {number}
*/
export function parsePort(text) {
if (text === "") {
throw new PortError(text, "empty");
}
if (!/^[0-9]+$/.test(text)) {
throw new PortError(text, "not a number");
}
const port = Number(text);
if (port < 1 || port > 65535) {
throw new PortError(text, "out of range");
}
return port;
}
/**
* Returns "port N", or the message of the PortError.
* @param {string} text
* @returns {string}
*/
export function checkPort(text) {
try {
return `port ${parsePort(text)}`;
} catch (e) {
// A catch clause takes each exception, so test the type and throw the rest again.
if (e instanceof PortError) {
return e.message;
}
throw e;
}
}
checkPort.test.js 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-custom-error-type/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { checkPort, parsePort, PortError } from "./checkPort.js";
const cases = [
["valid", "8080", "port 8080"],
["not-a-number", "x80", "invalid port 'x80': not a number"],
["too-large", "65536", "invalid port '65536': out of range"],
["empty", "", "invalid port '': empty"],
["zero", "0", "invalid port '0': out of range"],
["one", "1", "port 1"],
["largest", "65535", "port 65535"],
["leading-zeros", "0080", "port 80"],
["negative", "-1", "invalid port '-1': not a number"],
["leading-space", " 80", "invalid port ' 80': not a number"],
["overflow", "99999999999999999999", "invalid port '99999999999999999999': out of range"],
];
for (const [name, text, want] of cases) {
test(name, () => {
assert.equal(checkPort(text), want);
});
}
test("fields", () => {
assert.throws(
() => parsePort("x80"),
(e) => e instanceof PortError && e.name === "PortError" && e.text === "x80" && e.reason === "not a number",
);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-custom-error-type/.
/** The text is not a valid TCP port number. */
export class PortError extends Error {
readonly text: string;
readonly reason: string;
constructor(text: string, reason: string) {
super(`invalid port '${text}': ${reason}`);
// Without this line, the name is "Error" in messages and stack traces.
this.name = "PortError";
this.text = text;
this.reason = reason;
}
}
/** Returns the port number in text, or throws a PortError. */
export function parsePort(text: string): number {
if (text === "") {
throw new PortError(text, "empty");
}
if (!/^[0-9]+$/.test(text)) {
throw new PortError(text, "not a number");
}
const port = Number(text);
if (port < 1 || port > 65535) {
throw new PortError(text, "out of range");
}
return port;
}
/** Returns "port N", or the message of the PortError. */
export function checkPort(text: string): string {
try {
return `port ${parsePort(text)}`;
} catch (e) {
// A catch clause takes each exception, so test the type and throw the rest again.
if (e instanceof PortError) {
return e.message;
}
throw e;
}
}
checkPort.test.ts 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-custom-error-type/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { checkPort, parsePort, PortError } from "./checkPort.ts";
const cases: [string, string, string][] = [
["valid", "8080", "port 8080"],
["not-a-number", "x80", "invalid port 'x80': not a number"],
["too-large", "65536", "invalid port '65536': out of range"],
["empty", "", "invalid port '': empty"],
["zero", "0", "invalid port '0': out of range"],
["one", "1", "port 1"],
["largest", "65535", "port 65535"],
["leading-zeros", "0080", "port 80"],
["negative", "-1", "invalid port '-1': not a number"],
["leading-space", " 80", "invalid port ' 80': not a number"],
["overflow", "99999999999999999999", "invalid port '99999999999999999999': out of range"],
];
for (const [name, text, want] of cases) {
test(name, () => {
assert.equal(checkPort(text), want);
});
}
test("fields", () => {
assert.throws(
() => parsePort("x80"),
(e: unknown) => e instanceof PortError && e.name === "PortError" && e.text === "x80" && e.reason === "not a number",
);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-custom-error-type/.
// Package port reads a TCP port number and reports a bad one with its own error type.
package port
import (
"errors"
"fmt"
)
// PortError reports that a text is not a valid TCP port number.
type PortError struct {
Text string
Reason string
}
// Error makes *PortError satisfy the error interface.
func (e *PortError) Error() string {
return fmt.Sprintf("invalid port '%s': %s", e.Text, e.Reason)
}
// ParsePort returns the port number in text. The type of the result is
// error, not *PortError, so a nil result is a nil error.
func ParsePort(text string) (int, error) {
if text == "" {
return 0, &PortError{Text: text, Reason: "empty"}
}
for _, c := range text {
if c < '0' || c > '9' {
return 0, &PortError{Text: text, Reason: "not a number"}
}
}
port := 0
for _, c := range text {
port = port*10 + int(c-'0')
if port > 65535 {
return 0, &PortError{Text: text, Reason: "out of range"}
}
}
if port == 0 {
return 0, &PortError{Text: text, Reason: "out of range"}
}
return port, nil
}
// CheckPort returns "port N", or the message of the PortError.
func CheckPort(text string) string {
port, err := ParsePort(text)
var pe *PortError
if errors.As(err, &pe) {
return pe.Error()
}
if err != nil {
panic(err) // ParsePort returns no other error.
}
return fmt.Sprintf("port %d", port)
}
check_port_test.go 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-custom-error-type/.
package port
import (
"errors"
"testing"
)
var cases = []struct {
name, text, want string
}{
{"valid", "8080", "port 8080"},
{"not-a-number", "x80", "invalid port 'x80': not a number"},
{"too-large", "65536", "invalid port '65536': out of range"},
{"empty", "", "invalid port '': empty"},
{"zero", "0", "invalid port '0': out of range"},
{"one", "1", "port 1"},
{"largest", "65535", "port 65535"},
{"leading-zeros", "0080", "port 80"},
{"negative", "-1", "invalid port '-1': not a number"},
{"leading-space", " 80", "invalid port ' 80': not a number"},
{"overflow", "99999999999999999999", "invalid port '99999999999999999999': out of range"},
}
func TestCheckPort(t *testing.T) {
for _, c := range cases {
if got := CheckPort(c.text); got != c.want {
t.Errorf("%s: got %q, want %q", c.name, got, c.want)
}
}
}
func TestFields(t *testing.T) {
_, err := ParsePort("x80")
var pe *PortError
if !errors.As(err, &pe) || pe.Text != "x80" || pe.Reason != "not a number" {
t.Errorf("got %#v", err)
}
if _, err := ParsePort("80"); err != nil {
t.Errorf("got %#v, want nil", err)
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-custom-error-type/.
use std::error::Error;
use std::fmt;
/// Why a text is not a valid TCP port number.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Reason {
Empty,
NotANumber,
OutOfRange,
}
/// Reports that a text is not a valid TCP port number.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PortError {
pub text: String,
pub reason: Reason,
}
impl fmt::Display for Reason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Reason::Empty => "empty",
Reason::NotANumber => "not a number",
Reason::OutOfRange => "out of range",
})
}
}
impl fmt::Display for PortError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "invalid port '{}': {}", self.text, self.reason)
}
}
// Debug and Display are enough; source() keeps its default, None.
impl Error for PortError {}
/// Returns the port number in text, or a PortError.
pub fn parse_port(text: &str) -> Result<u16, PortError> {
let fail = |reason| PortError { text: text.to_string(), reason };
if text.is_empty() {
return Err(fail(Reason::Empty));
}
if !text.bytes().all(|b| b.is_ascii_digit()) {
return Err(fail(Reason::NotANumber));
}
let mut port: u32 = 0;
for b in text.bytes() {
port = port * 10 + u32::from(b - b'0');
if port > 65535 {
return Err(fail(Reason::OutOfRange));
}
}
if port == 0 {
return Err(fail(Reason::OutOfRange));
}
Ok(port as u16)
}
/// Returns "port N", or the message of the PortError.
pub fn check_port(text: &str) -> String {
match parse_port(text) {
Ok(port) => format!("port {port}"),
Err(e) => e.to_string(),
}
}
tests/check_port_test.rs 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-custom-error-type/.
use algo_define_a_custom_error_type::{check_port, parse_port, PortError, Reason};
#[test]
fn cases() {
let cases: &[(&str, &str, &str)] = &[
("valid", "8080", "port 8080"),
("not-a-number", "x80", "invalid port 'x80': not a number"),
("too-large", "65536", "invalid port '65536': out of range"),
("empty", "", "invalid port '': empty"),
("zero", "0", "invalid port '0': out of range"),
("one", "1", "port 1"),
("largest", "65535", "port 65535"),
("leading-zeros", "0080", "port 80"),
("negative", "-1", "invalid port '-1': not a number"),
("leading-space", " 80", "invalid port ' 80': not a number"),
("overflow", "99999999999999999999", "invalid port '99999999999999999999': out of range"),
];
for &(name, text, want) in cases {
assert_eq!(check_port(text), want, "{name}");
}
}
#[test]
fn fields() {
let want = PortError { text: "x80".to_string(), reason: Reason::NotANumber };
assert_eq!(parse_port("x80"), Err(want));
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/define-a-custom-error-type/.
# Bash has no error types. parse_port reports an error with its exit status
# and puts the fields of the error in two global variables. Call it without
# $( ), because a command substitution runs in a subshell, and the variables
# that it sets do not come back.
# parse_port TEXT
# Sets PORT on success and returns 0. Sets PORT_ERROR_TEXT and
# PORT_ERROR_REASON and returns 1 on an error.
parse_port() {
local text=$1 value=0 i
PORT_ERROR_TEXT=$text
if [[ -z $text ]]; then
PORT_ERROR_REASON="empty"
return 1
fi
if [[ ! $text =~ ^[0-9]+$ ]]; then
PORT_ERROR_REASON="not a number"
return 1
fi
for ((i = 0; i < ${#text}; i++)); do
value=$((value * 10 + ${text:i:1}))
if ((value > 65535)); then
PORT_ERROR_REASON="out of range"
return 1
fi
done
if ((value == 0)); then
PORT_ERROR_REASON="out of range"
return 1
fi
PORT=$value
return 0
}
# check_port TEXT
# Prints "port N", or the message of the error.
check_port() {
if parse_port "$1"; then
echo "port $PORT"
else
echo "invalid port '$PORT_ERROR_TEXT': $PORT_ERROR_REASON"
fi
}
test_check_port.bats 31 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/define-a-custom-error-type/.
setup() {
source "$BATS_TEST_DIRNAME/check_port.sh"
}
check() { # check TEXT WANT
local got
got=$(check_port "$1")
[ "$got" = "$2" ] || { printf 'got: %s\nwant: %s\n' "$got" "$2"; return 1; }
}
@test "valid" { check "8080" "port 8080"; }
@test "not-a-number" { check "x80" "invalid port 'x80': not a number"; }
@test "too-large" { check "65536" "invalid port '65536': out of range"; }
@test "empty" { check "" "invalid port '': empty"; }
@test "zero" { check "0" "invalid port '0': out of range"; }
@test "one" { check "1" "port 1"; }
@test "largest" { check "65535" "port 65535"; }
@test "leading-zeros" { check "0080" "port 80"; }
@test "negative" { check "-1" "invalid port '-1': not a number"; }
@test "leading-space" { check " 80" "invalid port ' 80': not a number"; }
@test "overflow" { check "99999999999999999999" "invalid port '99999999999999999999': out of range"; }
@test "fields" {
parse_port x80 || true
[ "$PORT_ERROR_TEXT" = x80 ]
[ "$PORT_ERROR_REASON" = "not a number" ]
}
References
- Errors and Exceptions, The Python Tutorial, 8.6 User-defined Exceptions
- Error, MDN Web Docs, Custom error types; Error.prototype.name
- Creating Exception Classes, The Java Tutorials, Choosing a Superclass
- Class Exception, Java SE 25 API, the class description
- Best practices for exceptions, .NET documentation, Custom exception types
- How to create user-defined exceptions, .NET documentation, the introduction
- std::runtime_error, cppreference.com, the description; Member functions
- Andrew Gerrand, Error handling and Go, The Go Blog, 12 July 2011, The error type
- Package errors, Go standard library, func As; func AsType
- std::error::Error, Rust standard library, the trait description
- thiserror, docs.rs, the crate description; Details
- Exit Status, Bash Reference Manual, the first paragraph
- Command Execution Environment, Bash Reference Manual, the subshell paragraph
- Built-in Exceptions, The Python Standard Library, the introduction
- Frequently Asked Questions (FAQ), The Go Programming Language, Why is my nil error value not equal to nil?
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag PHJT60 Edit this page History Report an error Markdown