How to handle errors while using Glib.Settings in Vala?
Asked Answered
C

2

6

I am using Glib.Settings in my Vala application. And I want to make sure that my program will work okay even when the schema or key is not available. So I've added a try/catch block, but if I'm using the key that doesn't exist, the program segfaults. As I understood, it doesn't even reach the catch statement. Here is the function that uses 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 program output is:

(main:27194): GLib-GIO-ERROR **: Settings schema 'my_scheme' does not contain a key named 'token1'
Trace/breakpoint trap (core dumped)

(of course I'm using my real scheme string instead of my_scheme) So can you suggest me where I'm wrong?

China answered 4/11, 2014 at 18:39 Comment(0)
P
3

The methods in GLib.Settings, including get_string do not throw exceptions, they call abort inside the library. This is not an ideal design, but there isn't anything you can do about it.

In this case, the correct thing to do is fix your schema, install into /usr/share/glib-2.0/schemas and run glib-compile-schemas on that directory (as root).

Vala only has checked exceptions, so, unlike C#, a method must declare that it will throw, or it is not possible to do so. You can always double check the Valadoc or the VAPI to see.

Prepotency answered 4/11, 2014 at 22:29 Comment(1)
I have right schema, I just wanted to be sure that someone didn't remove my key or schema and my program won't segfault after this.China
H
3

I know this is super late, but I was looking for the same solution so I thought I'd share one. As @apmasell said, the GLib.Settings methods don't throw exceptions—they just abort instead.

However, you can do a SettingsSchemaSource.lookup to make sure the key exists first. You can then 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");
}
Hatch answered 21/1, 2019 at 18:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.