How do I see errors encountered in async coroutines/tasks?

There will be no error message in the RPEL if an error is encountered in an async task, unless you check the state of the task. I find it super difficult to detect errors in async tasks when the tasks are not in the top level scope.
Example:

function f()
    wait(Timer(1))
    undeclaredvar
end
function g()
    @async f()
    nothing
end
g()
# there will be no way to find out the error about undeclaredvar

Is there a way to print out the error message as soon as an error happens in a task?

You can do it like that:

function f()
    wait(Timer(1))
    undeclaredvar
end

function g()
    return @async f()
end

julia> t = g()
Task (runnable) @0x0000000111b10010

julia> t
Task (failed) @0x0000000111b10010
UndefVarError: undeclaredvar not defined
f at /Users/paul/.julia/dev/tmp/test.jl:4 [inlined]
(::var"#9#10")() at ./task.jl:358

If you have a task variable, you can see the task status or – if it failed – the stack trace.

1 Like

or – after rereading your question :slightly_smiling_face:

function f()
	try
    	wait(Timer(1))
		undeclaredvar
	catch exc
		println(stacktrace())
		println(exc)
	end
end

function g()
	@async f()
	nothing
end

julia> g()

julia> Base.StackTraces.StackFrame[f() at test.jl:7, (::var"#11#12")() at task.jl:358]
UndefVarError(:undeclaredvar)
julia> 

julia>
1 Like

See also this related topic.