when I started to look at OTP, there are basically three behavior, gen_server, FSM, event, But there is an example of the inets application, I saw that it defined a customised behavior -behavior(inets_service). So how can the user define a customised behavior, and what can it do you for?
-
"For people hitting this page:" The answers available below might change because the method for defining custom behavior has changed after Erlang R14 otp release. https://erlangcentral.org/wiki/index.php?title=Defining_Your_Own_Behaviour may provide some information – anuj pradhan Aug 06 '15 at 11:20
-
An updated discussion about this (with an example) is here: http://stackoverflow.com/questions/32336854/how-to-use-a-callback-function-in-an-erlang-behaviour/32337438#32337438 – zxq9 Sep 02 '15 at 05:05
2 Answers
Custom behaviors allow you to specify a contract. This contract is given by a list of function names/arities that must exist in a module implementing that behaviour. It is essentially just convenience to make sure you declared all functions.
As an example, you could define a module which has gen_server
behavior and then omit the handle_info/2
function from it. The behavior-check will then error out because you are missing part of the contract.
That is all there is to it! To implement them, one defines a special function in the behavior-defining module, behavior_info/1
which tells the Erlang system about behaviors.
inets
defines an inets_service
behavior because it then serves as a contract for pluings to the inets
system.

- 18,739
- 3
- 42
- 47
-
If define a gen_server behaviour and omit the handle_info/2 from it. The behaviour-check will the **warn** out not **error** out. – mingchaoyan Mar 11 '14 at 11:24
cowboy demo
-module(cowboy_middleware).
-type env() :: [{atom(), any()}].
-export_type([env/0]).
-callback execute(Req, Env)
-> {ok, Req, Env}
| {suspend, module(), atom(), [any()]}
| {halt, Req}
| {error, cowboy:http_status(), Req}
when Req::cowboy_req:req(), Env::env().
erlang used -callback custom behavious.

- 15,750
- 31
- 68
- 83

- 11
- 2