Ruslan_K
Ruslan_K

Reputation: 423

delphi Invalid enum value '_24170'

I have my dll, it contains function:

function GetPdfReport(
  //this is string representation of MyEnum
  AStringParam : Pchar
): TByteDynArray; stdcall; export;

var
//my vars

begin
  try
    try
      //i try to pass incorrect string value on purpose to get exception
      MyEnumVariable := TRttiEnumerationType.GetValue<MyEnum>(AStringParam);

      //code hide
    except
      on E : Exception do
        begin
          //log error
          Log.Error(E.ClassName + ' : ' + E.Message, 'errors');
        end;
    end;
  finally
    //dispose
  end;

Then i get exception:

The InnerException message was 'Invalid enum value '_24170' cannot be deserialized into type 'MyEnum'.

I want log exception message with string value that i passed as parameter but not some unclear numbers like '_24170'. How can I do this?

Update:

Let's say i have MyEnum with 3 values (One, Two, Three), and when i pass to my function string "Five" i want to see exception like this:

Invalid enum value 'Five' cannot be deserialized into type 'MyEnum'.

Thanks.

Upvotes: 0

Views: 401

Answers (1)

David Heffernan
David Heffernan

Reputation: 613013

The code that you present does not raise an exception in case the supplied text does not match one of the enum values. Instead a value of -1 is returned. Of course, -1 is not a valid enum value so that makes TRttiEnumerationType.GetValue a rather questionable method if you wish to perform error handling.

You would need to test for this yourself. Rather than using TRttiEnumerationType it might be simpler to go directly to GetEnumValue, which returns an integer and so makes error checking a little simpler to write.

var
  OrdinalValue: Integer;
  Value: MyEnum;
....
OrdinalValue := GetEnumValue(TypeInfo(MyEnum), AStringParam);
if OrdinalValue = -1 then
  // handle error
Value := MyEnum(OrdinalValue);

Naturally you'd want to wrap this in a method to make it re-usable.

Upvotes: 4

Related Questions