定义异常类型

异常处理

-- An error class: the metatable of its errors
local SimpleError = {kind = "SimpleError"}
SimpleError.__index = SimpleError

function SimpleError.new(message)
  return setmetatable({message = message},
                      SimpleError)
end

-- Unhandled, this error would end the script
local _, err = pcall(function()
  error(SimpleError.new("Oops!"))
end)

-- type: the error is a table, not a string
local err_type = type(err)
-- err_type = table

-- getmetatable gives the class
local is_simple = getmetatable(err) == SimpleError
-- is_simple = true

-- kind is found in the class
local err_kind = err.kind
-- err_kind = SimpleError
local err_message = err.message
-- err_message = Oops!

-- A text error has another type
local _, text_err = pcall(error, "Oops!", 0)
local text_type = type(text_err)
-- text_type = string

print("err_type = " .. err_type)
print("is_simple = " .. tostring(is_simple))
print("err_kind = " .. err_kind)
print("err_message = " .. err_message)
print("text_type = " .. text_type)