Cleaner error handling
I'm a fan of bottlepy [http://bottlepy.org/docs/dev/index.html] and have been playing around with lapis a lot lately. In an attempt to learn lapis I've been porting an API over into it and I've really missed being able to have finer control over http errors. For example in bottlepy you can do this:
@error(404)
def four_oh_four(err):
response.content_type = "application/json"
return json.dumps({'message': 'resource not found'})
Equivalently in lapis
app.handle_404 = function(self)
return { status = 404, layout = false, json = { message = "not found" }}
end
But lapis begins to become tedious when I want to do custom error handling for anything beyond a 404. For example, if a client was to POST to a route that didn't support that http verb. In bottlepy it is easy because behind the scenes bottle throws a HTTPError(405, ...), which is eventually caught be a default error handler. But you can also easily hook in by using the @error decorator:
@error(405)
def four_oh_five(err):
response.content_type = "application/json"
return None
@error(400)
def four_oh_oh(err):
response.content_type = "application/json"
msg = 'Malformed or Invalid request'
if err:
msg = err.body
return json.dumps({'message': msg})
This is really great because I can catch arbitrary HTTPErrors (using abort).
@get("/coffee")
def get_coffee():
# something goes wrong
abort(418, "I'm a teapot")
@error(418)
def four_one_eight(err):
response.content_type = "application/json"
return json.dumps({'message': err.body})
Which returns
> HTTP 418 I'm a teapot
...snip...
> {"message":"I'm a teapot"}
In lapis all I get is a error_handler override, which is limiting at the moment
app.handle_error = function(self, err, trace)
ngx.log(ngx.NOTICE, "There was an error! " .. err .. ": " ..trace)
lapis.Application.handle_error(self, err, trace)
end
handle_error is designed for rendering non-recoverable errors. From the docs:
The error handler should only be used to capture fatal and unexpected errors, expected errors are discussed in the Exception Handling guide.
For something like this you should use capture_errors and yield_error. You should abstract your error logic into a decorator function and then wrap your actions with it.
Here's a variation of the built in capture_errors_json that lets you set the status code:
local lapis_app = require("lapis.application")
local capture_errors, yield_error = lapis_app.capture_errors, lapis_app.yield_error
local function api_request(fn)
return capture_errors({
fn,
on_error = function(self)
local first_error = self.errors[1]
local status, message = unpack(first_error)
return {
status = status,
json = {
message = message
}
}
end
})
end
local function abort(status, message)
yield_error({ status, message })
end
app.get("/hello", api_request(function(self)
if not self.params.hello then
abort(418, "I'm a teapot")
end
return { json = { success = true } }
end))
How would I capture and respond with a 405 Unsupported Method when a route doesn't match the action and verb? As far as I can tell, Lapis uses error internally when this happens.
Hello,
I encountered the same issue. @leafo was able to help me with a work around that solved my issue. Here is a link to the relevant comment. https://github.com/leafo/lapis/issues/99#issuecomment-44505776
Closing old issue, open again if you want me to write an example.