Is GetLastError() kind of design pattern? Is it good mechanism?

前端 未结 7 1954
庸人自扰
庸人自扰 2021-02-12 15:27

Windows APIs uses GetLastError() mechanism to retrieve information about an error or failure. I am considering the same mechanism to handle errors as I am writing A

7条回答
  •  长情又很酷
    2021-02-12 15:53

    If your API is in a DLL and you wish to support clients that use a different compiler then you then you cannot use exceptions. There is no binary interface standard for exceptions.

    So you pretty much have to use error codes. But don't model the system using GetLastError as your exemplar. If you want a good example of how to return error codes look at COM. Every function returns an HRESULT. This allows callers to write concise code that can convert COM error codes into native exceptions. Like this:

    Check(pIntf->DoSomething());
    

    where Check() is a function, written by you, that receives an HRESULT as its single parameter and raises an exception if the HRESULT indicates failure. It is the fact that the return value of the function indicates status that allows this more concise coding. Imagine the alternative of returning the status via a parameter:

    pIntf->DoSomething(&status);
    Check(status);
    

    Or, even worse, the way it is done in Win32:

    if (!pIntf->DoSomething())
        Check(GetLastError());
    

    On the other hand, if you are prepared to dictate that all clients use the same compiler as you, or you deliver the library as source, then use exceptions.

提交回复
热议问题