leafo / lapis

A web framework for Lua and OpenResty written in MoonScript
http://leafo.net/lapis/
MIT License
3.12k stars 247 forks source link

Cannot capture errors in before filters #709

Closed karai17 closed 3 years ago

karai17 commented 3 years ago

I am working on a JSON API and I want to check a request's Authorization header to verify a user before I take any further actions on any request. I am trying to use capture_errors_json to capture errors, and a custom handler to handle them. When I do this, everything seems to flow correctly, errors get captured and the handler executes... Then the whole thing gets discarded and Lapis progresses to execute the action. I'm not really sure how to go about working around this aside from manually capturing errors inside the filters instead of using the built-in tools.

local capture = require("lapis.application").capture_errors_json
local handle  = require("utils.error").handle
app:before_filter(capture({ on_error=handle, require "apps.api.internal.before_auth" }))
return function(self)
    if self.req.headers["Authorization"] then
        local auth = mime.unb64(self.req.headers["Authorization"]:sub(7))
        local username, api_key = auth:match("^(.+)%:(.+)$")

        if not username or not api_key then
            assert_error(nil, "Corrupt auth!")
            -- this executes correctly but the results get tossed
        end

        local params = {
            username = username,
            api_key  = api_key
        }

        -- Get User
        self.api_user = assert_error(Users:get_api(params))
        return
    end

    -- Set basic User
    self.api_user = {
        id   = -1,
        role = -1
    }
end
karai17 commented 3 years ago

Ah! I just figured it out. If i self:write my handler's return value, it works as intended.

return self:write {
    status = self.errors[1].status,
    json   = self.errors
}