#returning errors from main?

1 messages · Page 1 of 1 (latest)

unreal oriole
#

What's the correct way to return either an u8 on error or void from main?

#

(Sorry if that sounds really stupid, I've been trying for the past few minutes and gave up)

hot ridge
#

wdym?

#

you can return an error with !void

#

if it errors it'll exit with exit code 1

#

custom exit codes require the use of u8 or !u8

#

or std.os.exit :)

unreal oriole
hot ridge
#

here's an example ig:
(untested)

pub fn main() u8 {
  myFunctionThatCanError() catch |err| return switch (err) {
    error.Amongus => 420,
    error.Bruh => 69,
    else => 1,
  };
  return 0;
}
hot ridge
hot ridge
#
pub fn main() !void {
  try myFunctionThatCanError();
}
unreal oriole
#

When I do

pub fn main() !u8 {
    failingFunction() orelse return 1;
}

I get "expected type ..., got void"

#

How can I return either void or an u8?

hot ridge
hot ridge
unreal oriole
#

Thanks.

hot ridge
#

main only allows returning void, !void, u8, or !u8 iirc

#

np

#

not sure why you'd want void or a u8 tho

unreal oriole
#

...How do I return an error from !void?

hot ridge
#

return error.MyError

unreal oriole
#

...?

#

what do I need to return exactly

hot ridge
#
pub fn myFunctionThatCanError() !void {
  return error.MyError;
}
#

I mean you just return the error

#

MyError being the error name

unreal oriole
#

what is MyError

hot ridge
#

it's a name

unreal oriole
#

what name

hot ridge
#

oh wait i might get your confusion

#

okay so

#
  • errors can't contain/carry values
  • errors are named
#

whenever you create an error it's added to the global error set

unreal oriole
#

Okay, which names can I use?

hot ridge
#

anything you want

unreal oriole
#

oh I can just use any?

#

nice!

hot ridge
#

error.HoRRIbleErrorNaMe

#

i believe error.@"bruh----====0" might even work (not sure)

unreal oriole
#

this works now!

pub fn main() !void {
    const sus = createAmogus() orelse return error.AmogusError;
}
hot ridge
#

or_?

#

are you using orelse on the createAmogus return value?

unreal oriole
#

oops I'm dumb

hot ridge
#

i don't think orelse works with errors, you'd have to use catch

unreal oriole
#

Thanks.

#

Sorry, the concept of returning errors that aren't numeric from main confused me