Erlang Error Handling
Contents |
Top of chapter Character Set Source File Encoding Data Types Top of chapter Terms Number Atom Bit Strings and Binaries Reference Fun Port Identifier haskell error handling Pid Tuple Map List String Record Boolean Escape Sequences Type
Ruby Error Handling
Conversions Pattern Matching Top of chapter Pattern Matching Modules Top of chapter Module Syntax Module python error handling Attributes Comments module_info/0 and module_info/1 functions Functions Top of chapter Function Declaration Syntax Function Evaluation Tail recursion Built-In Functions (BIFs) Types and Function Specifications Top of erlang error handling example chapter The Erlang Type Language Types and their Syntax Type Declarations of User-Defined Types Type Information in Record Declarations Specifications for Functions Expressions Top of chapter Expression Evaluation Terms Variables Patterns Match Function Calls If Case Send Receive Term Comparisons Arithmetic Expressions Boolean Expressions Short-Circuit Expressions List Operations Map Expressions Bit Syntax
Let It Crash Philosophy Of Erlang
Expressions Fun Expressions Catch and Throw Try Parenthesized Expressions Block Expressions List Comprehensions Bit String Comprehensions Guard Sequences Operator Precedence Preprocessor Top of chapter File Inclusion Defining and Using Macros Predefined Macros Macros Overloading Flow Control in Macros -error() and -warning() directives Stringifying Macro Arguments Records Top of chapter Defining Records Creating Records Accessing Record Fields Updating Records Records in Guards Records in Patterns Nested Records Internal Representation of Records Errors and Error Handling Top of chapter Terminology Exceptions Handling of Run-time Errors in Erlang Exit Reasons Processes Top of chapter Processes Process Creation Registered Processes Process Termination Message Sending Links Error Handling Monitors Process Dictionary Distributed Erlang Top of chapter Distributed Erlang System Nodes Node Connections epmd Hidden Nodes C Nodes Security Distribution BIFs Distribution Command-Line Flags Distribution Modules Compilation and Code Loading Top of chapter Compilation Code Loading Code Replacement Running a Function When a Module is Loaded Ports and P
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site About Us Learn more about Stack Overflow the company erlang try catch throw Business Learn more about hiring developers or posting ads with us Stack Overflow Questions Jobs erlang catch badarg Documentation Tags Users Badges Ask Question x Dismiss Join the Stack Overflow Community Stack Overflow is a community of 4.7 million programmers,
Erlang Exception Handling
just like you, helping each other. Join them; it only takes a minute: Sign up Erlang error handling philosophy - case vs throw up vote 6 down vote favorite 3 I'm writing a REST service in Erlang http://erlang.org/doc/reference_manual/errors.html and need to verify the received data before passing it to other internal functions for further processing; in order to do that, I'm currently using nested case expressions like this: case all_args_defined(Args) of true -> ActionSuccess = action(Args), case ActionSuccess of {ok, _} -> ...; {fail, reason} -> {fail, reason} end, _ -> {fail, "args not defined"} end, ... I realize this is kind of ugly, but this way I can provide detailed error http://stackoverflow.com/questions/6859645/erlang-error-handling-philosophy-case-vs-throw messages. Additionally, I don't think the usual make it crash philosophy is applicable here - I don't want my REST service to crash and be restarted every time somebody throws invalid arguments at it. However, I'm considering abandoning all those cases in favor of an umbrella try/catch block catching any badmatch errors - would this work? fun() -> true = all_args_defined(Args), {ok, _} = action(Args). %% somewhere else catch fun(). exception-handling error-handling erlang share|improve this question asked Jul 28 '11 at 13:22 Philip Kamenarsky 1,1252917 5 Just a comment on the "let it crash" philosophy: If you're writing code that in itself cannot do anything sensible with the error (like the code for your individual actions), you should program for the success case and just let it crash if something is not right. This keeps the code short and focused. However, at some points, you will want to handle errors - like in a supervisor, or in your REST receive-execute-reply loop. Then you set things up with links or try/catch so that the errors are propagated to that point and handled there and only there. –RichardC Jul 28 '11 at 16:46 Yea, that makes sense - I'm just too exception damaged from other... languages, so I try to avoid them when possible :) Erlang has a pretty
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site About Us http://stackoverflow.com/questions/4412640/how-to-get-try-catch-to-work-in-erlang Learn more about Stack Overflow the company Business Learn more about hiring developers or posting ads with us Stack Overflow Questions Jobs Documentation Tags Users Badges Ask Question x Dismiss Join the Stack Overflow https://mitnk.com/2012/05/exceptions_and_errors_in_erlang/ Community Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute: Sign up How to get try / catch to work error handling in erlang up vote 4 down vote favorite i'm pretty new to erlang and i'm trying to get a basic try / catch statement to work. I"m using webmachine to process some requests and all i really want to do is parse some JSON data and return it. In the event that the JSON data is invalid, I just want to return an error msg. Here is the erlang error handling code I have so far. (the JSON data is invalid) to_text(ReqData, Context) -> Body = "{\"firstName\": \"John\"\"lastName\": \"Smith\"}", try decode(Body) of _ -> {"Success! Json decoded!",ReqData,Context} catch _ -> {"Error! Json is invalid",ReqData,Context} end. decode(Body) -> {struct, MJ} = mochijson:decode(Body). The code compiles, but when i run it, and send a request for the text, i get the following error back. error,{error,{case_clause,{{const,"lastName"}, ": \"Smith\"}", {decoder,utf8,null,1,31,comma}}}, [{mochijson,decode_object,3}, {mochijson,json_decode,2}, {webmachine_demo_resource,test,1}, {webmachine_demo_resource,to_text,2}, {webmachine_demo_resource,to_html,2}, {webmachine_resource,resource_call,3}, {webmachine_resource,do,3}, {webmachine_decision_core,resource_call,1}]}} What exactly am i doing wrong? documentation says the "catch" statement handles all errors, or do i have to do something to catch a specific error that is thrown by mochijson:decode. Please any leads or advice would be helpful. Thanks. erlang try-catch share|improve this question edited Dec 11 '10 at 2:18 ndim 17.3k103145 asked Dec 10 '10 at 19:43 user436605 108311 add a comment| 1 Answer 1 active oldest votes up vote 13 down vote accepted The catch-clause "_ -> ..." only catches exceptions of the 'throw' class. To catch other kinds of exceptions, you need to write a pattern on the form "Class:Term -> ..." (i.e., the default Class is 'throw'). In your case: catch _:_ -> {"Error! Json is invalid",ReqData,Context} end When you do
function clause matching shop:cost(pear) (shop.erl, line 4) Raising an Exception: exit(Why) This is used when you really want to terminate the current process. If this exception is not caught, the message {’EXIT’,Pid,Why} will be broadcast to all processes that are linked to the current process. throw(Why) This is used to throw an exception that a caller might want to catch. In this case we document that our function might throw this exception. erlang:error(Why) This is used for denoting “crashing errors.” That is, something rather nasty has happened that callers are not really expected to handle. This is on par with internally generated errors. try...catch Syntax try FuncOrExpressionSequence of Pattern1 [when Guard1] -> Expressions1; Pattern2 [when Guard2] -> Expressions2; ... catch ExceptionType: ExPattern1 [when ExGuard1] -> ExExpressions1; ExceptionType: ExPattern2 [when ExGuard2] -> ExExpressions2; ... after AfterExpressions end Example: generate_exception(1) -> a; generate_exception(2) -> throw(a); generate_exception(3) -> exit(a); generate_exception(4) -> {'EXIT', a}; generate_exception(5) -> erlang:error(a). demo1() -> [catcher(I) || I <- [1,2,3,4,5]]. catcher(N) -> try generate_exception(N) of Val -> {N, normal, Val} catch throw:X -> {N, caught, thrown, X}; exit:X -> {N, caught, exited, X}; error:X -> {N, caught, error, X} end. Run it: 1> try_test:demo1(). [{1,normal,a}, {2,caught,thrown,a}, {3,caught,exited,a}, {4,normal,{'EXIT',a}}, {5,caught,error,a}] The other way to trap an exception is to use the primitive catch. When you catch an exception, it is converted into a tuple that describes the error. demo2() -> [{I, (catch generate_exception(I))} || I <- [1,2,3,4,5]]. Run it: 2> try_test:demo2(). [{1,a}, {2,a}, {3,{'EXIT',a}}, {4,{'EXIT',a}},