rikyoz / bit7z

A C++ static library offering a clean and simple interface to the 7-zip shared libraries.
https://rikyoz.github.io/bit7z
Mozilla Public License 2.0
627 stars 114 forks source link

[FR] Add error code member to BitException #25

Closed levicki closed 5 years ago

levicki commented 5 years ago

Current implementation of BitException only contains textual error message. If I want to know the exact reason for the error the only way I see is comparing strings which is really inefficient, error-prone, and subject to breaking if error strings are changed in the future.

Looking at the code, in most of the places where exceptions are thrown there is either an error code from the OS GetLastError() API (such as ERROR_MOD_NOT_FOUND if library path is wrong, or ERROR_FILE_NOT_FOUND if archive path is wrong) or a HRESULT from 7-Zip code.

It would be nice if an error code was added to BitException, preferrably as a HRESULT.

levicki commented 5 years ago

My current workaround:

} catch (BitException ex) {
    DWORD OSErrorCode = GetLastError();
    if (OSErrorCode != ERROR_SUCCESS) {
        return HRESULT_FROM_WIN32(OSErrorCode);
    } else {
        string  ErrorString(ex.what());
        string  ErrorRegexPattern = R"(^.*\(error code: (\-?[0-9]+)\).*$)";
        regex   ErrorRegex(ErrorRegexPattern, regex::ECMAScript | regex::optimize);
        smatch  Result;
        if (regex_match(ErrorString, Result, ErrorRegex)) {
            if (Result[1].matched) {
                Status = atoi(Result[1].str().c_str());
            } else {
                Status = E_FAIL;
            }
        }
    }
}
rikyoz commented 5 years ago

Current implementation of BitException only contains textual error message. If I want to know the exact reason for the error the only way I see is comparing strings which is really inefficient, error-prone, and subject to breaking if error strings are changed in the future.

Looking at the code, in most of the places where exceptions are thrown there is either an error code from the OS GetLastError() API (such as ERROR_MOD_NOT_FOUND if library path is wrong, or ERROR_FILE_NOT_FOUND if archive path is wrong) or a HRESULT from 7-Zip code.

It would be nice if an error code was added to BitException, preferrably as a HRESULT.

Yeah, you are right! At the beginning of this project, BitException was meant for simple debugging purposes, but indeed it now needs a refactoring! I think that adding a BitException::getErrorCode() method (returning a HRESULT as you suggest) is a good idea and it would be useful for the users.

Thank you for your feedback!

levicki commented 5 years ago

You are welcome.