lud

lud

Hello,

When writing libraries it is often useful to define behaviours for library users to implement.
In general, those behaviour callbacks must return a specific type, like {:reply, term, term} or {:ok, term}.

Callbacks should be properly documented and then user-implemented, so it is generally fine to exit or raise if the return value does not adhere to the spec.

In Erlang, this is done by throwing an error with {:bad_return_value, retval}. For instance:

defmodule GS do
  def init(_), do: :foo
end

GenServer.start_link(GS, [])

In that case the error will be formatted as bad return value: :foo by the Elixir Exception module, but it does not tell what did not behave properly.

This is a general problem not related to processes. In libraries you can find code like this:

case user_mod.some_callback("hello") do
  {:ok, v} -> {:ok, do_stuff(v)}
  {:error, _} = err -> err
  other -> exit({:bad_return_value, other})
end

I use this pattern a lot. But the stacktrace will not contain user_mod.some_callback, which is a problem.

You can find occurences in OTP code where the bad return tuple includes the MFA that misbehaved, and it is formatted as MyApp.Application.start(:normal, []) returned a bad value: :foo though I cannot find where this is formatted (currently testing on OTP 27.3.

Erlang processes have some kind of helpful output:

-module(foo).
-export([init/1]).
init([]) -> foo.

Calling that module:

gen_server:start_link(foo, [], []).

Gives the “initial call” information in the crash report:

=CRASH REPORT==== 19-Nov-2025::09:32:46.515514 ===
  crasher:
    initial call: foo:init/1
    pid: <0.96.0>
    registered_name: []
    exception exit: {bad_return_value,foo}
      in function  gen_server:init_it/6 (gen_server.erl, line 2222)

This is for processes but I’m not sure anything standard exists for generic functional code.

How do you handle this case in your libraries or behaviours that you expect your coworkers to implement correctly?

Do you think that a ReturnError exception could be helpful ? (not fan of the name but if follows the pattern of ArgumentError).

So we could use it like that:

case user_mod.some_callback("hello") do
  {:ok, v} -> {:ok, do_stuff(v)}
  {:error, _} = err -> err
  other -> raise ReturnError, module: user_mod, function: :some_callback, value: other
end

And/Or what do you think of a special case in the exception module that would treat {:bad_return_value, {{m,f,a}, term} when is_atom(m) and is_atom(f) and is_list(a) in a special way? (Not sure if backwards compatible though).

Thank you :slight_smile:

Showing Posts 1 to 7

lud

lud OP

Hello @josevalim What do you think?

I’ve just had a case where we have a function that takes a callback, and the callback is supposed to return a result tuple. If it does not we raise an ArgumentError. In a sense it’s correct, the function does not respect the contract, so the function is a bad argument. But it’s kinda far fetched.

krasenyp

krasenyp

I usually raise ArgumentError but it’s not concise.

fuelen

fuelen

Hammox.Protect helps in tests

lud

lud OP

I don’t want to enforce that on users of my libraries, and not all return values are from behaviours callbacks.

For instance returning :not_a_list from the callback to Enum.flat_map breaks a contract.

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

To what extent is this going to get handled by the new type system?

lud

lud OP

The same as for ArgumentError I believe. Many cases can be discovered, but not all of them.

christhekeele

christhekeele

I’ve reinvented the same pattern in many of my libraries: a namespaced Lib.BadReturnError with a :call parameter that takes AST and Macro.to_strings it when formatting the error message (or some variation thereof), usually with a :reason string field to indicate what was expected and something like a :got field to contain the unexpected value.

I can see the utility of such a thing in the stdlib, if only to empower library developers (over using it much itself) as a good idiom for user feedback. I would argue that the language of UnexpectedReturnError is probably better than BadReturnError. There are also many places I can see stdlib opting to use it, such as the new empty lists errors from hd and tl. And possibly the language could convert erlang {:bad_return_value, got} into first-class ones the way it does for some cases of ex. ArgumentError today, which is another argument for inclusion in the std lib itself.

— All posts loaded —

Where Next? Top

Trending in Discussions Top

wmnnd
Hey folks, I wanted to share with you a project I’ve been working on for a while: It’s an Open Source (AGPLv3) newsletter tool. Think Ma...
New
axelson
Hi there! :wave: @frigidcode and I (but mostly him) have been running an Elixir Book club, we’re almost done with Designing Elixir Syste...
New
alexslade
Fly’s CEO posted this recently - Turn And Face The Strange · The Fly Blog It says that Fly is going all-in on sprites, which is a worry ...
New
sntran
In my third year of college, around 2010, I found Erlang. A few years later, I found Elixir. I liked the ideas at once: many small proces...
New
Ganna
Hi everyone, I have 8 years of production experience with Erlang/OTP and I’m just starting to get to know Elixir. What would you learn f...
New
johnkirkham
A note on form. Joe Armstrong, co-creator of the Erlang programming language, died in April 2019. What follows is a work of narrative non...
New
gtcode
I’ve been tinkering with Lynx (by José) via hold_ledger. I used AI to write the code, a separate specification, the tests, and the Lean p...
New

Other Trending Topics Top

dominicletz
Hey there, I haven’t seen a list of useful Elixir specific skills for the popular AI tools yet so I’m starting one here with my first. ...
New
mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
webofbits
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself. My main conc...
#ai
New
OndrejValenta
(I just needed to vent somewhere and LinkedIn is full of hope, or hype, I’m not sure which exactly) AI dream has many faces, but general...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews