Note that there are some explanatory texts on larger screens.

plurals
  1. POIs GetLastError() kind of design pattern? Is it good mechanism?
    primarykey
    data
    text
    <p>Windows APIs uses <code>GetLastError()</code> mechanism to retrieve information about an error or failure. I am considering the same mechanism to handle errors as I am writing APIs for a proprietary module. My question is that is it better for API to return the error code directly instead? Does <code>GetLastError()</code> has any particular advantage? Consider the simple Win32 API example below:</p> <pre><code>HANDLE hFile = CreateFile(sFile, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { DWORD lrc = GetLastError(); if (lrc == ERROR_FILE_EXISTS) { // msg box and so on } } </code></pre> <p>As I was writing my own APIs I realized <code>GetLastError()</code> mechanism means that <code>CreateFile()</code> must set the last error code at all exit points. This can be a little error prone if there are many exit points and one of them maybe missed. Dumb question but is this how it is done or there is some kind of design pattern for it?</p> <p>The alternative would be to provide an extra parameter to the function which can fill in the error code directly so a separate call to <code>GetLastError()</code> will not be needed. Yet another approach can be as below. I will stick with the above Win32 API which is good example to analyzer this. Here I am changing the format to this (hypothetically).</p> <pre><code>result = CreateFile(hFile, sFile, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); if (result == SUCCESS) { // hFile has correct value, process it } else if (result == FILE_ALREADY_EXIT ) { // display message accordingly return; } else if ( result == INVALID_PATH ) { // display message accordingly. return; } </code></pre> <p>My ultimate question is what is the preferred way to return error code from an API or even just a function since they both are the same? </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload