File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change @@ -338,6 +338,44 @@ namespace atoms {
338338}
339339```
340340
341+ ### Result types
342+
343+ When it comes to NIFs, errors often indicate unexpected failures and
344+ raising an exception makes sense, however you may also want to handle
345+ certain errors gracefully by returning `:ok`/`:error` tuples, similarly
346+ to usual Elixir functions. Fine provides `Ok<...>` and `Error<...>`
347+ types for this purpose.
348+
349+ ```cpp
350+ fine::Ok<>()
351+ // :ok
352+
353+ fine::Ok<int64_t>(1)
354+ // {:ok, 1}
355+
356+ fine::Error<>()
357+ // :error
358+
359+ fine::Error<std::string>("something went wrong")
360+ // {:error, "something went wrong"}
361+ ```
362+
363+ You can use ` std::variant ` to express a union of possible result types
364+ a NIF may return:
365+
366+ ``` cpp
367+ std::variant<fine::Ok<int64_t >, fine::Error<std::string>> find_meaning (ErlNifEnv * env) {
368+ if (...) {
369+ return fine::Error< std::string > ("something went wrong");
370+ }
371+
372+ return fine::Ok<int64_t>(42);
373+ }
374+ ```
375+
376+ Note that if you use a particular union frequently, it may be convenient
377+ to define a type alias with `using`/`typedef` to keep signatures brief.
378+
341379## Prior work
342380
343381Some of the ideas have been previously explored by Serge Aleynikov (@saleyn)
You can’t perform that action at this time.
0 commit comments