You can create named location directives and pass errors to them. Inside the named error handler you can use something like redis to keep track of the stats. Here is some un-tested pseudo'ish code
error_page 502 @502;
location @502 {
content_by_lua '
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000)
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then ngx.say("failed to connect: ", err) return end
-- Here you would likely increment the key. The below set is just an example.
ok, err = red:set("ERROR:503", 1)
if not ok then ngx.say("failed to set dog: ", err) return end