When should I throw errors versus return Option<T>?

I’ve read this but I’m still unclear when a public canister method should throw Error.reject("...") versus returning a null wrapped in an Option<T>.

It changes how the callsite has to handle the error (in JS land, dealing with a rejected promise versus an always resolved promise but with a union of two types of values).

It seems like most code uses Option<T> instead of throwing Error objects. Is there a particularly good reason to use one or another in a public method, or is it mostly a stylistic choice? (I know throwing is not allowed in a private synchronous function, so for consistency’s sake it might be better to use Option<T> and Result<Ok, Err> everywhere in the Motoko code.

I tried to summarize my understanding in another thread.

1 Like