How to catch errors thrown by GDScript objects?

Godot Version

4.6.2

Question

This question is not about the GDScript scripting language, but about the little-documented GDScript class. I can write the following:

var scr = GDScript.new()
scr.source = "print('foo')"
scr.reload()
scr.new()

This prints “foo” to stdout.

The problem is, if the source has some sort of error, then the game will simply crash without a proper backtrace. If it is a syntax error, then one might be able to find it from the error message, but if it is an assignment error, then the search will be awful.

In most languages, I would wrap the call to scr.new() inside some flavour of try and handle the exception myself. Since Godot does not have exceptions, what can I do? I want two things:

  1. I want to know in which script the error occurred. No script I create this way will have more than a few lines, so I am fine with not having a backtrace inside the scr variable, but I would at least like to know which GDScript object contains the error.
  2. What I would really like would be for my game to not crash on error. At least when the code has no side effects, I would just like to know that it failed and be able to handle the situation myself.

How can I achieve this?

You don’t.

You could start by ensuring that reload() returned OK to catch syntax errors. Unfortunately, I don’t have any suggestions for runtime errors from new().

Unfortunately, reload() returns OK on basically anything, including missing indentation and unmatched parentheses. Actually, I have yet to make it return anything else.

Edit: never mind, I somehow lost the error code along the way. Your suggestion is a very good first step indeed.