Errors C++

Errors C++ is a C++ package that provides utilities for error handling. This package mainly consists of the errors::Error class, representing an object that may contain an error.

This package serves as an alternative to error handling using try-catch exceptions, commonly found in C++ code. It facilitates error handling by returning values, following the style of Go’s error handling.

Key Features

This package provides the following key features:

Integration

To integrate this package into your C++ project, you can build and install it locally using CMake:

cmake -B build .
cmake --build build --config Release
cmake --install build

Once installed, you can use it in your CMake project as the Errors package:

find_package(Errors 1.0.0 REQUIRED CONFIG)

add_executable(foo foo.cpp)
target_link_libraries(foo PRIVATE errors::errors)

Alternatively, you can also integrate this package using CPM.cmake:

cpmaddpackage(gh:threeal/errors-cpp@1.0.0)

add_executable(foo foo.cpp)
target_link_libraries(foo PRIVATE errors)

Usage

This package contains an errors::Error class, which represents an error object. Functions that may produce errors should return this object so that the error can be handled properly.

errors::Error read_file(const char* filepath);

int main() {
  const auto err = read_file(filepath);
  if (err) {
    // Handle the error.
  }

  // Continue processing if no error.
}

For functions returning errors::Error, use errors::nil() function to signify no error or return an error object created from the errors::make() function.

errors::Error read_file(const char* filepath) {
  std::ifstream file(filepath);
  if (!file.is_open()) {
    return errors::make("failed to open file");
  }

  // Process with no error.

  return errors::nil();
}

Alternatively, an error object can also be created with a formatted message in the style of fmtlib using errors::format() function.

if (!file.is_open()) {
  return errors::format("failed to open '{}'", filepath);
}

For more details and examples, refer to the examples directory.

API Docs

class Error

Represents error information.

Use this class as the return type for functions that may produce errors. This class has two state: either it contains an error or not. Use boolean operations to check whether an object contains an error or not.

errors::Error print_hex(const char* number_str) {
  int number = std::atoi(number_str);
  if (number_str[0] != '0' && number == 0) {
    return errors::make("is not a number");
  }

  std::cout << std::hex << number << std::endl;
  return errors::nil();
}

int main() {
  // Print "7b".
  auto err = print_hex("123");
  assert(!err);

  // Error.
  err = print_hex("not a number");
  assert(err);
}

Public Functions

std::string_view message() const

Returns the error message.

Returns the error message as a string view. If the object does not contain an error, it will return the string “no error” instead.

const auto err = errors::make("unknown error");
const auto no_err = errors::nil();

// Print "unknown error, no error".
std::cout << err.message() << ", " << no_err.message() << std::endl;
Returns:

The error message.

explicit operator bool() const

Checks whether it contains an error or not.

const auto err = errors::make("unknown error");
assert(err);

const auto no_err = errors::nil();
assert(!no_err);

Returns:

true if it contains an error, otherwise false.

Friends

friend std::ostream &operator<<(std::ostream &os, const errors::Error &err)

Writes the string representation of an error object to the given output stream.

This operator allows an error object to be printed to the output stream using the << operator. The error message will be written to the output stream.

const auto err = errors::make("unknown error");

// Print "error: unknown error".
std::cout << err << std::endl;
Parameters:
  • os – The output stream.

  • err – The error object.

Returns:

The output stream.

Error errors::make(std::string_view msg)

Creates a new error object with the given message.

Use this function to create a new error object with the given message. Be aware that creating a new error object with an empty message will treat the object as containing an error. Use errors::nil instead if you want to create an empty error object.

auto err = errors::make("unknown error");
assert(err);

err = errors::make("");
assert(err);
Parameters:

msg – The error message.

Returns:

A new error object.

const Error &errors::nil()

Gets a constant reference of an empty error.

Use this function to initialize a new empty error object. If copied onto another error object, it will set that object to be treated as not containing an error.

const auto no_err = errors::nil();
assert(!no_err);

auto err = errors::make("unknown error");
err = errors::nil();
assert(!err);
Returns:

A constant reference of an empty error.

Format Component

template<typename ...T>
Error errors::format(fmt::format_string<T...> fmt, T&&... args)

Creates a new error object with a formatted message.

Use this function to create a new error object with a formatted message. Refer to fmtlib’s formatting syntax for more information on formatting a message for the error object.

const int code = 404;
const auto err = errors::format("HTTP error {}", code);

// Print "error: HTTP error 404".
fmt::format("{}\n", err)
Template Parameters:

T – Variadic template parameter pack for format arguments.

Parameters:
  • fmt – A format string for the message.

  • args – Format arguments.

Returns:

A new error object.

License

https://opensource.org/wp-content/uploads/2022/10/osi-badge-dark.svg https://opensource.org/wp-content/uploads/2022/10/osi-badge-light.svg

This project is licensed under the terms of the MIT License.

Copyright © 2023-2024 Alfi Maulana

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.