Menu
CoddyTech

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 -1

An 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 range

A 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 icon

Challenge

Easy

Write the function parse_level(text) above _ready(). It returns a dictionary:

  • If text is not a whole number: {"ok": false, "error": "Not a number"}
  • If the number is less than 1 or greater than 99: {"ok": false, "error": "Level must be between 1 and 99"}
  • Otherwise: {"ok": true, "value": level}, where level is the number as an int

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 42

For the input 150, the output is:

Error: Level must be between 1 and 99

Try 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
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online GDScript compiler