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
  •  | 
  •  

문제

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?

도움이 되었습니까?

해결책

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;

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top