Skip to content

Commit 8edc08e

Browse files
committed
Handle crashes in exercise 18.1
1 parent 0a02c88 commit 8edc08e

File tree

2 files changed

+16
-6
lines changed

2 files changed

+16
-6
lines changed

chapter_18/exercise_1/src/shell1.erl

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
%% Visit http://www.pragmaticprogrammer.com/titles/jaerlang2 for more book information.
88
%%---
99
-module(shell1).
10-
-export([start/1]).
10+
-export([start/1, bf/2]).
1111

1212
start(Browser) ->
1313
Browser ! #{cmd => append_div, id => scroll,

chapter_18/exercise_1/src/webserver.erl

+15-5
Original file line numberDiff line numberDiff line change
@@ -26,16 +26,26 @@ websocket_handle(_Frame = {text, Msg}, State) ->
2626
% chose to use this so I could reuse the shell.erl code from the book
2727
% without having to modify it to handle binary keys.
2828
Data = jsx:decode(Msg, [{labels, atom}, return_maps]),
29-
io:format("Received message: ~p~n", [Data]),
3029
shell1 ! {self(), Data},
3130
{ok, State};
3231
websocket_handle(Frame, State) ->
33-
io:format("Received frame: ~p~n", [Frame]),
3432
{ok, State}.
3533

3634
websocket_info({log, Text}, State) ->
3735
{reply, {text, Text}, State};
38-
websocket_info(Info, State) ->
36+
websocket_info(Info, State) when is_map(Info) ->
37+
% If Info is a map we assume it is a message from shell1
3938
Bin = jsx:encode([Info]),
40-
io:format("Sending message: ~p~n", [Bin]),
41-
{reply, {text, Bin}, State}.
39+
{reply, {text, Bin}, State};
40+
websocket_info({'EXIT', _Pid, Failure}, State) ->
41+
% Show the user the crash
42+
BV = shell1:bf("#> <font color='red'>~p</font><br>", [Failure]),
43+
Message = #{cmd => append_div, id => scroll, txt => BV},
44+
Bin = jsx:encode([Message]),
45+
46+
% Restart
47+
Pid = spawn_link(shell1, start, [self()]),
48+
_ = register(shell1, Pid),
49+
{reply, {text, Bin}, State};
50+
websocket_info(_Info, State) ->
51+
{ok, State}.

0 commit comments

Comments
 (0)