C/C++中自定義錯誤信息

在程序執行過程中往往會遇到一些錯誤的出現,此時需要做出相應都應對方法,同時輸出錯誤信息。每個人 都有各自的方法。比如我,直接打印一段字符串
printf("Error: Connect fail.")
亦或者臨時使用,更省事打印“111”(我相信不止我這麼幹,雖然都知道這是不規範操作)。
今天就學到了一個非常有意思都出錯信息輸出。來自微信公衆號strongerHuang的文章:

/* 聲明出錯代碼 */
#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   /* Memeroy is not enough */
#define ERR_SERV_DOWN   5   /* Service down try later */
#define ERR_UNKNOW_INFO 6   /* Unknow 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 time out */

/* 聲明出錯信息 */
char* errmsg[] = {
/* 0 */ "No error",
/* 1 */ "Open file error",
/* 2 */ "Failed in sending/receiving a message",
/* 3 */ "Bad arguments",
/* 4 */ "Memeroy is not enough",
/* 5 */ "Service is down; try later",
/* 6 */ "Unknow information",
/* 7 */ "A socket operation has failed",
/* 8 */ "Permission denied",
/* 9 */ "Bad configuration file format",
/* 10 */ "Communication time out",
};

/* 聲明錯誤代碼全局變量 */
long errno = 0;

/*
 -----------------------------------
 *函數名:perror
 *功  能:打印錯誤信息
 *參  數:info :錯誤位置(函數名或者標號用於定位錯誤位置 )
 *返回值:無
 -----------------------------------
 */
void perror( char* info)
{
  if ( info ){
    printf("%s: %s\n", info, errmsg[errno] );
    return;
  }
  printf("Error: %s\n", errmsg[errno] );
}

那麼,如何使用呢?

bool CheckPermission( char* userName )
{
  if ( strcpy(userName, "root") != 0 ){
  errno = ERR_PERMISSION_DENIED;/* 記錄錯誤代碼,非魔鬼數字 清晰易懂 */
  return (FALSE);
}

...
}

main()
{
  ...
  if (! CheckPermission( username ) ){
  perror("main()");
}
...
}

如此錯誤輸出可以統一管理方便使用,有意思的一段代碼喲

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章