#How to raise error on function that returns String?

10 messages · Page 1 of 1 (latest)

winter lodge
#

I have a function that returns a String but needs to validate the input before returning it. I've seen that in Godot there is no try/catch/exceptions but error codes are expected to be returned and parsed instead. However, if my function returns String, how can I return an error code if the inputs are invalid?

urban snow
#

The pattern I've been personally following for situations like this is similar to Linux's errno. Basically, the object has a field called _last_error with only public get access. On error, this is populated in the function that errored and it returns default of the type (like empty String).

#

I suppose another option could be to wrap String with a new RefCounted type and use it as an out parameter of the function. Then return Error instead.

#

🙂

winter lodge
#

thanks for the super quick response! i just have one question, your mention about RefCounted got me curious, im reading about it in the docs because i didn't know about it, but i can't quite understand how would you use it in this situation?

#

like, you create a RefCounted using the string if no errors arise, and set reference count = 1; but create the RefCounted without the string (or empty string) and set reference count to 0?

urban snow
#

Good question 🙂

#

Basically, you would create a new class (class_name RefCountedString extends RefCounted) which has a field of the string (var value: String = ""). You would create one of these in the calling code, then pass it in as a parameter to the function. Because RefCounted types are pass by reference, the function can change its value: String and the calling code can call my_ref_counted_string.value after the function returns to get the value.

winter lodge
#

i see, sounds interesting, i'll definitely give it a shot. Thanks again for your time answering my question and have a nice day!

#

(btw i dont know how to mark this question as solved lol)