[英]Convert errno to exit codes
I'm working on lib which uses a lot of file system functions.我正在研究使用大量文件系统函数的 lib。
What I want is that my function returns various of error codes (not just -1 as error) depending on errno in case file system function fails.我想要的是我的 function 根据errno返回各种错误代码(不仅仅是 -1 作为错误),以防文件系统 function 失败。
Although I could use errno values directly but I want to create some abstraction layer between my functions error codes and system errno (eg my error values begins on -1000 and are negative whereas errno values are positive).虽然我可以直接使用errno 值,但我想在我的函数错误代码和系统 errno之间创建一些抽象层(例如,我的错误值从 -1000 开始并且是负数,而 errno 值是正数)。
My question what is the best way to implement it.我的问题是什么是实现它的最佳方式。
For now I see two possible solution:现在我看到两种可能的解决方案:
typedef enum {
MY_ERROR_EPERM = -1104, /* Operation not permitted */
MY_ERROR_ENOENT = -1105, /* No such file or directory */
// ...
} MyReturnCodes_t;
int ErrnoToErrCode(unsigned int sysErrno) {
int error = ENOSYS;
switch(sysErrno) {
case EPERM: error = MY_ERROR_EPERM; break;
case ENOENT: error = MY_ERROR_ENOENT; break;
// ...
}
return error;
}
#define ERR_OFFSET -1000
typedef enum {
MY_ERROR_EPERM = ERR_OFFSET - EPERM, /* Operation not permitted */
MY_ERROR_ENOENT = ERR_OFFSET - ENOENT, /* No such file or directory */
MY_ERROR_ESRCH = ERR_OFFSET - ESRCH, /* No such process */
// ...
} MyReturnCodes_t;
Which way is more constant?哪种方式更稳定?
One more point: This library should be used both on QNX and Linux OS , what is the proper way to align errno codes (which different in some cases)?还有一点:这个库应该在QNX和Linux OS上使用,对齐 errno 代码的正确方法是什么(在某些情况下不同)?
I´d go for a std::map
in a dedicated function.我在专用 function 中为
std::map
提供 go。 You don't have to care about gaps or anything as long as you use the provided error macros:只要您使用提供的错误宏,您就不必关心间隙或任何事情:
#include <iostream>
#include <errno.h>
#include <map>
namespace MyError
{
enum MyReturnCode: int
{
MY_INVALID_VAL = 0 , /* Invalid Mapping */
MY_ERROR_EPERM = -1104, /* Operation not permitted */
MY_ERROR_ENOENT = -1105, /* No such file or directory */
};
MyReturnCode fromErrno(int e)
{
static const std::map<int, MyReturnCode> mapping {
{ EPERM, MY_ERROR_EPERM},
{ ENOENT, MY_ERROR_ENOENT}
};
if(mapping.count(e))
return mapping.at(e);
else
return MY_INVALID_VAL;
}
}
int main()
{
std::cout << MyError::fromErrno(ENOENT) << std::endl;
std::cout << MyError::fromErrno(42) << std::endl;
return 0;
}
http://coliru.stacked-crooked.com/a/1da9fd44d88fb097 http://coliru.stacked-crooked.com/a/1da9fd44d88fb097
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.