File: error.cpp

package info (click to toggle)
boost1.88 1.88.0-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 576,932 kB
  • sloc: cpp: 4,149,234; xml: 136,789; ansic: 35,092; python: 33,910; asm: 5,698; sh: 4,604; ada: 1,681; makefile: 1,633; pascal: 1,139; perl: 1,124; sql: 640; yacc: 478; ruby: 271; java: 77; lisp: 24; csh: 6
file content (75 lines) | stat: -rw-r--r-- 2,076 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//
// Copyright (c) 2019-2025 Ruben Perez Hidalgo (rubenperez038 at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#include <boost/asio/awaitable.hpp>
#include <boost/pfr/config.hpp>
#if defined(BOOST_ASIO_HAS_CO_AWAIT) && BOOST_PFR_CORE_NAME_ENABLED

//[example_http_server_cpp20_error_cpp

#include <boost/system/error_category.hpp>

#include <iostream>
#include <mutex>

#include "error.hpp"

namespace {

// Converts an orders::errc to string
const char* error_to_string(orders::errc value)
{
    switch (value)
    {
    case orders::errc::not_found: return "not_found";
    case orders::errc::order_invalid_status: return "order_invalid_status";
    case orders::errc::product_not_found: return "product_not_found";
    default: return "<unknown orders::errc>";
    }
}

// The category to be returned by get_orders_category
class orders_category final : public boost::system::error_category
{
public:
    // Identifies the error category. Used when converting error_codes to string
    const char* name() const noexcept final override { return "orders"; }

    // Given a numeric error belonging to this category, convert it to a string
    std::string message(int ev) const final override
    {
        return error_to_string(static_cast<orders::errc>(ev));
    }
};

// The error category
static const orders_category g_category;

// The std::mutex that guards std::cerr
static std::mutex g_cerr_mutex;

}  // namespace

//
// External interface
//
const boost::system::error_category& orders::get_orders_category() { return g_category; }

std::unique_lock<std::mutex> orders::lock_cerr() { return std::unique_lock{g_cerr_mutex}; }

void orders::log_error(std::string_view header, boost::system::error_code ec)
{
    // Lock the mutex
    auto guard = lock_cerr();

    // Logging the error code prints the number and category. Add the message, too
    std::cerr << header << ": " << ec << " " << ec.message() << std::endl;
}

//]

#endif