完整示例
首先,定义错误代码和错误信息数组:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
// 声明出错代码
#define ERR_NO_ERROR 0 /* No error */
#define ERR_OPEN_FILE 1 /* Open file error */
#define ERR_SEND_MESG 2 /* Sending a message error */
#define ERR_BAD_ARGS 3 /* Bad arguments */
#define ERR_MEM_NONE 4 /* Memory is not enough */
#define ERR_SERV_DOWN 5 /* Service down try later */
#define ERR_UNKNOW_INFO 6 /* Unknown information */
#define ERR_SOCKET_ERR 7 /* Socket operation failed */
#define ERR_PERMISSION 8 /* Permission denied */
#define ERR_BAD_FORMAT 9 /* Bad configuration file */
#define ERR_TIME_OUT 10 /* Communication timeout */
// 声明出错信息
char* errmsg[] = {
/* 0 */ "No error",
/* 1 */ "Open file error",
/* 2 */ "Failed in sending/receiving a message",
/* 3 */ "Bad arguments",
/* 4 */ "Memory is not enough",
/* 5 */ "Service is down; try later",
/* 6 */ "Unknown information",
/* 7 */ "A socket operation has failed",
/* 8 */ "Permission denied",
/* 9 */ "Bad configuration file format",
/* 10 */ "Communication timeout",
};
// 声明错误代码全局变量
long errno = ERR_NO_ERROR;
// 打印出错信息函数
void perror(const char* info) {
if (info) {
printf("%s: %s\n", info, errmsg[errno]);
return;
}
printf("Error: %s\n", errmsg[errno]);
}
// 示例函数,演示如何设置和处理错误
bool CheckPermission(const char* userName) {
if (strcmp(userName, "root") != 0) {
errno = ERR_PERMISSION;
return false;
}
errno = ERR_NO_ERROR;
return true;
}
int main() {
const char* username = "guest";
if (!CheckPermission(username)) {
perror("main()");
}
// 其他代码...
return 0;
}
关键点说明
-
错误代码与错误信息的统一管理:定义错误代码和对应的错误信息数组,有利于统一错误信息的输出格式,便于维护和管理。
-
全局错误变量:使用全局变量
errno
来保存错误代码,使得不同函数间可以方便地传递和检查错误状态。 -
统一的错误输出函数:定义
perror
函数,用于输出错误信息。这样,可以保证所有错误信息的输出格式一致。 -
错误检查与设置:在函数中检查错误条件并设置相应的错误代码,然后在调用函数中检查返回值并输出错误信息。
通过以上方法和建议,可以实现一个既有共性又有个性的错误信息处理机制,提高代码的可维护性和可读性。