Search code examples
mysqldartdart-mirrors

Is there a way to inquire if a class contains an instance variable with some known name?


When intercepting an error from MySql, it's not known beforehand what will be the contents of the error-class passed to me. So I code:

.catchError((firstError) {
  sqlMessage = firstError.message; 
  try {        
    sqlError = firstError.osError;
  } catch (noInstanceError){
    sqlError = firstError.sqlState;
  }
});

In this specific case I'd like to know whether e contains instance variable osError or sqlState, as any of them contains the specific errorcode. And more in general (to improve my knowledge) would it be possible write something like if (firstError.instanceExists(osError)) ..., and how?


Solution

  • This should do what you want:

    import 'dart:mirrors';
    
    ...
    
    // info about the class declaration
    reflect(firstError).type.declarations.containsKey(#osError);
    
    // info about the current instance
    var m = reflect(firstError).type.instanceMembers[#osError];
    var hasOsError = m != null && m.isGetter;