#Can you pass an error inside a structure?

1 messages · Page 1 of 1 (latest)

rough narwhal
#

I am trying to do something like this, is this possible. (The reason is that I am returning errors while tokenizing, but I need to catch these errors and attach line numbers)

error_info.zig:

line: usize = 0,
column: usize = 0,
type: error{ErrorType} = .unknown,

test "test error type" {
    const e = self{
        .line = 1,
        .column = 2,
        .type = .unexpected_eof,
    };
    expect(e.line == 1);
}

This wont compile:

error_info.zig:41:27: error: expected type 'error{ErrorType}', found '@TypeOf(.enum_literal)'
type: error{ErrorType} = .unknown,```
#

Originally I just had an ErrorInfo with an ErrorType enum, but I cant work out a way to easily return that inside the tokenizer as an error.

#

Alternatively, this also fails but with a different equally unclear error:

type: error{ErrorType} = ErrorType.unknown,
                    ~~~~~~~~~^~~~~~~~
error_info.zig:41:35: note: 'error.unknown' not a member of destination error set
#

This also creates a different error again.

type: error{ErrorType} = error{unknown},
error_info.zig:41:26: error: expected type 'error{ErrorType}', found 'type'
type: error{ErrorType} = error{unknown},
grave seal
#

You can use error.Foo

#

error.Foo is the same as error{Foo}.Foo and all errors are actually one single type in the end. So all error{Foo} is the same.

lyric belfry
#

If you want an error payload (message, context info), an out-param is the typical solution.

rough narwhal
rough narwhal
terse flax
# rough narwhal Thanks, I tried that thougj and it doesnt work. Neither of these work: ``` type...

const ErrorSet = error{Name1, Name2, ...}; declares an error set, to get an error instance you do it like an enum: ErrorSet.Name1

error.Name1 is a special shortcut for error{Name1}.Name1, ie create an error set of one error and make an instance of that error. since error sets are coercible this works. (you can return error.Name1 from a function that returns ErrorSet, because errors are based on their literal names)

#

so for your scenario, you could either do type: error{spelling} = error.spelling, which means type can only hold the error values inside the curly braces (which in this case is only the error spelling). or type could be type: anyerror = error.spelling, which means type can hold any error value

#

just think of it like an enum with different syntax and more lenient coercions

#

just like enum { a, b, c } declares a new enum type and you get an instance with either Enum.a or .a when it can be inferred, error { A, B, C } declares a new error set and you get an instance with either ErrorSet.A or error.A when it can be inferred

rough narwhal
#

Thank you. Using "anyerror" just got me past the stumbling block I am at for now. I think I understand how the error type is working conceptually. But in terms of syntax and how to use it more concretely I am still learning. Thanks.