clugg / sm-json

A pure SourcePawn JSON encoder/decoder.
GNU General Public License v3.0
82 stars 8 forks source link

[Feature Req] Error Buffer #26

Closed MAGNAT2645 closed 2 years ago

MAGNAT2645 commented 2 years ago

Would be good to have the ability to get last error instead of just logging it to the errors log.

Example code:

public void OnPluginStart() {
    RegAdminCmd( "sm_mycmd", CMD_MyCommand, ADMFLAG_ROOT );
}

Action CMD_MyCommand(int client, int args) {
    char szBuffer[512];
    GetCmdArgString( szBuffer, sizeof szBuffer );

    JSON_Object hObject = json_decode( szBuffer, JSON_DECODE_SINGLE_QUOTES );

    if ( !hObject ) {
        json_get_last_error( szBuffer, sizeof szBuffer );
        ReplyToCommand( client, "Invalid JSON! Error: %s", szBuffer );
        LogError( "%s", szBuffer ); // you could log the error manually if you really want
        return Plugin_Handled;
    }

    // do something with hObject

    return Plugin_Handled;
}

The error buffer could be a static string in the json.inc library.

static char g_szLastError[512];

stock void json_get_last_error(char[] buffer, int maxlength) {
    strcopy( buffer, maxlength, g_szLastError );
}

// "internal" function to use in the array.inc, object.inc etc.
// this could be used instead of LogError (for example in json_decode())
stock void json_set_last_error(const char[] error) {
    strcopy( g_szLastError, sizeof g_szLastError, error );
}
clugg commented 2 years ago

Thanks for the suggestion! I've just released v4.1.0 which adds support for this.