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

StackOverflow https://stackoverflow.com/questions/21974178

  •  15-10-2022
  •  | 
  •  

Pergunta

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?

Foi útil?

Solução

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;

Outras dicas

Günter's answer correctly shows how to use mirrors, however for your particular use case I'd recommend using an "is" check instead of mirrors. I don't know the mysql API specifically but it could look something like this:

.catchError((error) {
   sqlMessage = error.message;
   if (error is MySqlException) {
     sqlError = error.sqlState;
   } else if (error is OSError) {
     sqlError = error.errorCode;
   }
})

Perhaps ask James Ots, the author of sqljocky for advice.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top