Returning Error Codes
Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 69 of 78.
A function that can fail has to tell its caller whether it worked, so the caller can decide what to do next. There are three common ways to return a failure.
A special value that a real result can never be. You know this from find(), which returns -1 for a missing element, and get(), which returns null:
func slot_of(items: Array, item: String) -> int:
for i in range(items.size()):
if items[i] == item:
return i
return -1An Error code. Godot's own functions report failures with the global enum Error: OK (0) means success, and every other value names a problem, such as ERR_INVALID_PARAMETER (31). error_string() turns a code into text:
func check_volume(level: int) -> Error:
if level < 0 or level > 100:
return ERR_PARAMETER_RANGE_ERROR
return OK
func _ready():
var result := check_volume(150)
if result != OK:
print("Error: ", error_string(result)) # Error: Parameter out of rangeA dictionary, when the caller needs either a value or the reason it failed. The "ok" key says which one it got:
func parse_speed(text: String) -> Dictionary:
if not text.is_valid_float():
return {"ok": false, "error": "Not a number"}
return {"ok": true, "value": float(text)}The caller checks result["ok"] first, and reads result["value"] only when it is true.
Challenge
EasyWrite the function parse_level(text) above _ready(). It returns a dictionary:
- If
textis not a whole number:{"ok": false, "error": "Not a number"} - If the number is less than
1or greater than99:{"ok": false, "error": "Level must be between 1 and 99"} - Otherwise:
{"ok": true, "value": level}, wherelevelis the number as anint
In _ready(), call parse_level() with the line of input. If the result is ok, print Level set to and the value. Otherwise, print Error: and the error message.
For the input 42, the output is:
Level set to 42For the input 150, the output is:
Error: Level must be between 1 and 99Try it yourself
extends Node
# Write the parse_level function here
func _ready():
var text := OS.read_string_from_stdin()
# Call parse_level and print the result
pass
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String MethodsSearching in StringsReplace and TrimSplit and JoinRecap - Username Check4Dictionaries Part 2
Nested DictionariesArrays of DictionariesMerging DictionariesCopying DictionariesRecap - Frequency Counter2Advanced Decision Making
Match With VariablesMatch GuardsArray PatternsDictionary PatternsMembership ChecksRecap - Command Parser5Contact Book Application
Display MenuAdd Contact8Student Records Manager
Project OverviewAdd Student3Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysJagged ArraysCommon 2D Array PatternsRecap - Game Board6Sets with Dictionaries
What is a Set?Dictionary as a SetAdding and RemovingUnion and IntersectionSet DifferenceRecap - Remove Duplicates9Advanced Data Aggregation
Summing ValuesFinding Minimum and MaximumCustom SortingRecap - Dictionary Sorter12Basic Error Handling
What is Error Handling?Validating InputGuard ClausesReturning Error CodesRecap - Safe DivisionPractice on your own: Online GDScript compiler