Home
Ratchet Library :: Error Handling
API  ·  Manual

Types of Failures

An error raised in Lua code generally halts execution and outputs a message describing what happened and where. This type of erroring is good for things that can and should be fixed by the programmer. Generally, if a user sees this kind of error, you would want them to submit a bug report.

Many functions, especially when dealing with socket programming, can fail without there actually being a problem with the application. For example, when connecting to a remote host that is currently turned off, you would usually rather try again with a different host or eloquently tell the user what happened.

Error Objects

Good practice when using the ratchet library is making library calls with a high probability of failure in protected mode with pcall() or xpcall().

Calling a ratchet function within pcall() is slightly uglier and harder to read, but the benefits are worth it. The first result of from pcall will always be boolean true or false, depending on whether or not the call threw an error or not. If the result is true, the call executed without error and the remaining results are the return values from the function. If the result is false, an error occured and the remaining result is an error message or object.

In the case of "hard" errors, those thrown by Lua internally or errors indicating programmer error, the error will be a string value describing the error. It is generally best to let the errors propogate so they can be noticed and dealt with.

In the case of "soft" errors, such as a socket call timing out or a connection being refused, the error will be a table object with a set of attributes and methods providing information about what happened. The most useful decision making attribute is the error code or name, which will usually match up with an errno code.

To check for this code, the error object has a method error:is() or you can use the long form ratchet.error.is(). The long form is safer; if the error is a string and not an error object then using error:is() will itself throw an error. Here's an example of good usage:

local success, err = pcall(socket.connect, socket)
if not success then
    if ratchet.error.is(err, "ETIMEDOUT") then
        logger.warning("Connection to host timed out: "..host)
        return false
    elseif ratchet.error.is(err, "ECONNREFUSED") then
        logger.warning("Connection to host refused: "..host)
        return false
    else
        error(err)
    end
end

See the man pages for the socket system call you're using for details on exactly what errors it can fail with.

See the API documentation ratchet.error for details on other pieces of information available in error objects.




Last modified:  Sun, 17 Aug 2014 09:32:32 -0400
Author:  ian.good