How to handle errors when using Glib.Settings in Vala?
I am using Glib.Settings in my Vala app. And I want to make sure that my program will work fine even if the schema or key is not available. So I added a try / catch block, but if I use a key that doesn't exist, the program segfaults. As I understand it, it doesn't even get to the catch statement. Here's a function that uses the settings:
GLib.Settings settings;
string token = "";
try
{
settings = new GLib.Settings (my_scheme);
token = settings.get_string("token1");
}
catch (Error e)
{
print("error");
token = "";
}
return token;
And the output of the program:
(main:27194): GLib-GIO-ERROR **: Settings schema 'my_scheme' does not contain a key named 'token1'
Trace/breakpoint trap (core dumped)
(of course I am using my real schema string instead of my_scheme) Can you suggest me where I am going wrong?
source to share
Methods in GLib.Settings
including get_string
do not throw exceptions, they are called abort
inside the library. It's not perfect design, but there is nothing you can do about it.
In this case, the right thing to do is fix your schema, install in /usr/share/glib-2.0/schemas
and run glib-compile-schemas
in that directory (as root).
Vala only checks for exceptions, so unlike C #, the method must declare that it will throw, or it cannot be done. You can always double check Valadoc or VAPI to see.
source to share
I know this is very late, but I was looking for the same solution, so I decided to share it. As @apmasell said, GLib.Settings methods don't throw exceptions - they just abort them.
However, you can do SettingsSchemaSource.lookup to make sure the key exists first. Then you can also use has_key
for specific keys. For example,
var settings_schema = SettingsSchemaSource.get_default ().lookup ("my_scheme", false);
if (settings_schema != null) {
if (settings_schema.has_key ("token1")) {
var settings = new GLib.Settings ("my_scheme");
token = settings.get_string("token1");
} else {
critical ("Key does not exist");
}
} else {
critical ("Schema does not exist");
}
source to share