Make console.error format GError correctly
See #511 (closed) for context
In JavaScript, there is Error
, which is well-supported by console.error
:
gjs> console.error(new Error('wow'))
(gjs:657652): Gjs-Console-CRITICAL **: 19:49:29.199: Error: wow
...
But in GJS we also have GError
which is used by GNOME APIs. GError is similar to Error but is not a subclass of it.
If you log a GError with console.error
, you currently get a simple object properties overview because console
doesn't know about GError
.
gjs> try {imports.gi.Gio.File.new_for_path('/foo').load_contents(null) } catch (err) { console.error(err) }
(gjs:657652): Gjs-Console-CRITICAL **: 19:52:51.496: {
"stack": "@typein:2:47\n@<stdin>:1:42\n",
"fileName": "typein",
"lineNumber": 2,
"columnNumber": 47
}
...
It's not very good for developer experience because it doesn't even show what kind of error it is. That is the reason we still use logError
instead of console.error
in Workbench.
Instead, console.error
should be able to format a GError properly to show something like this
gjs> try {imports.gi.Gio.File.new_for_path('/foo').load_contents(null) } catch (err) { console.error(err) }
(gjs:657652): Gjs-Console-CRITICAL **: 19:52:51.496: Gio.IOErrorEnum: Error opening file /foo: No such file or directory
...
similar to what logError
does.
You can build and test GJS using GNOME Builder.
Since we use the same formatter for other log levels log
, debug
, ... this will also work with console.log
and so on.
You can find the formatter here https://gitlab.gnome.org/GNOME/gjs/-/blob/61024387d42677dc9a1590daee2762119765efee/modules/esm/console.js#L42
https://docs.gtk.org/glib/struct.Error.html
else if (item instanceof GLib.Error) {
...
}