std::error_code的使用

概述

std::error_code主要包括两方面: error id和category, 要实现自己定义的error_code, 也就需要定义自己的error id和category.
如果只使用error id(例如Linux的errno)的话, 不同服务分开开发可能相同的errno代表的含义不同, 因此需要使用error id代表状态, 和category表示该error_code所在的域.

定义自己的error id: error num enum

  • 定义自己的enum class:
enum class FlightsErrc {
    NonexistentLocations = 10,
    DatesInThePast,
    InvertedDates,
    NoFlightsFound = 20,
    ProtocolViolation = 30,
    ConnectionError,
    ResourceError,
    Timeout
};
  • 特例化std::is_error_code_enum:
namespace std {
template <>
struct is_error_code_enum<FlightsErrc> : true_type {};
}
  • 声明并实现std::error_code make_error_code(Your_Error_Enum):
    在头文件中声明:
// .h文件
std::error_code make_error_code(FlightsErrc);
// .cpp文件
std::error_code make_error_code(FlightsErrc errc) {
	// theFlightErrCategory是自己的category的一个实例, 见下面
    return {static_cast<int>(errc), theFlightErrCategory};
}

定义自己的error_category

注意声明和实现自己的error_category在cpp源文件的一个编译单元即可, 其它使用的地方只需要该结构的一个实例地址.
需要继承std::error_category, 并实现name()和message()这两个纯虚函数.

struct FlightsErrCategory : std::error_category {
        const char *name() const noexcept override;
        std::string message(int ev) const override;
    };

    const char *FlightsErrCategory::name() const noexcept {
        return "flights";
    }

    std::string FlightsErrCategory::message(int ev) const {
    	// enum class需要static_cast
        switch (static_cast<FlightsErrc>(ev))
        {
        case FlightsErrc::NonexistentLocations:
            return "nonexistent airport name in request";
            break;
        case FlightsErrc::DatesInThePast:
            return "request for a date from the past";
            break;
        case FlightsErrc::InvertedDates:
            return "requested flight return date before departure date";
            break;
        case FlightsErrc::NoFlightsFound:
            return "no filight combination found";
            break;
        case FlightsErrc::ProtocolViolation:
            return "received malformed request";
            break;
        case FlightsErrc::ConnectionError:
            return "could not connect to server";
            break;
        case FlightsErrc::ResourceError:
            return "insufficient resources";
            break;
        case FlightsErrc::Timeout:
            return "processing timed out";
            break;
        // 这里需要default用于传入非enum class范围的值
        default:
            return "(unrecognized error)";
        }
    }

	// 注意定义一个category的示例用于实现make_error_code方法
    const FlightsErrCategory theFlightErrCategory {};

完整代码示例

error_code.h

#ifndef ERROR_CODES_H
#define ERROR_CODES_H

#include <system_error>

enum class FlightsErrc {
    NonexistentLocations = 10,
    DatesInThePast,
    InvertedDates,
    NoFlightsFound = 20,
    ProtocolViolation = 30,
    ConnectionError,
    ResourceError,
    Timeout
};

namespace std {
template <>
struct is_error_code_enum<FlightsErrc> : true_type {};
}
std::error_code make_error_code(FlightsErrc);

#endif

error_code.cpp

#include "error_codes.h"

namespace {
    struct FlightsErrCategory : std::error_category {
        const char *name() const noexcept override;
        std::string message(int ev) const override;
    };

    const char *FlightsErrCategory::name() const noexcept {
        return "flights";
    }

    std::string FlightsErrCategory::message(int ev) const {
        switch (static_cast<FlightsErrc>(ev))
        {
        case FlightsErrc::NonexistentLocations:
            return "nonexistent airport name in request";
            break;
        case FlightsErrc::DatesInThePast:
            return "request for a date from the past";
            break;
        case FlightsErrc::InvertedDates:
            return "requested flight return date before departure date";
            break;
        case FlightsErrc::NoFlightsFound:
            return "no filight combination found";
            break;
        case FlightsErrc::ProtocolViolation:
            return "received malformed request";
            break;
        case FlightsErrc::ConnectionError:
            return "could not connect to server";
            break;
        case FlightsErrc::ResourceError:
            return "insufficient resources";
            break;
        case FlightsErrc::Timeout:
            return "processing timed out";
            break;
        default:
            return "(unrecognized error)";
        }
    }

    const FlightsErrCategory theFlightErrCategory {};
}

std::error_code make_error_code(FlightsErrc errc) {
    return {static_cast<int>(errc), theFlightErrCategory};
}

参考内容

https://blog.csdn.net/mightbxg/article/details/108290083?app_version=5.15.4&csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%22108290083%22%2C%22source%22%3A%22weixin_44708428%22%7D&utm_source=app
http://blog.think-async.com/2010/04/system-error-support-in-c0x-part-1.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
`std::error_code`是C++11标准中定义的一个类型,用于表示错误码。它通常与`std::error_category`一起使用,后者定义了一组错误码的类别。使用`std::error_code`和`std::error_category`可以方便地表示和处理各种错误类型。 下面是一个简单的例子: ```cpp #include <system_error> #include <iostream> enum class my_error_code { ok = 0, file_not_found, invalid_argument }; namespace std { template <> struct is_error_code_enum<my_error_code> : true_type {}; } std::error_code make_error_code(my_error_code e) { static const std::error_category& category = []() -> const std::error_category& { static std::error_category instance{"my_error_category"}; return instance; }(); return {static_cast<int>(e), category}; } int main() { std::error_code ec = my_error_code::file_not_found; std::cout << ec.message() << std::endl; return 0; } ``` 在上面的例子中,我们首先定义了一个枚举类型`my_error_code`,表示三种错误码。然后我们通过特化`std::is_error_code_enum`模板,告诉编译器`my_error_code`是一个`std::error_code`可以处理的错误码类型。接着定义了一个`make_error_code`函数,用于将枚举类型转换为`std::error_code`对象。在`make_error_code`函数中,我们定义了一个静态变量表示错误码的类别,然后返回一个由错误码和类别构成的`std::error_code`对象。 在`main`函数中,我们首先将枚举类型转换为`std::error_code`对象,然后调用`message`方法输出错误消息。 以上是一个简单的使用`std::error_code`的例子,通过了解`std::error_code`的用法,我们可以更好地处理各种错误类型。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值