Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how to handle error? #4

Open
Isma399 opened this issue May 4, 2022 · 2 comments
Open

how to handle error? #4

Isma399 opened this issue May 4, 2022 · 2 comments

Comments

@Isma399
Copy link

Isma399 commented May 4, 2022

Hello,
thanks for this lib.
We try to use it to localize mail sender, testing step was ok with some ips.
But passing it in prod breaks.
Is there a way to handle error when IP is in mmdb but not data :

# cat test.lua
local mm = require 'maxminddb'
local db = mm.open('/var/lib/libmaxminddb/GeoLite2-City.mmdb')

function geoip(ip)
    local res, status = db:lookup(ip)
    return res:get("country", "iso_code")
end

for k, ip in pairs({'8.8.8.8', '165.72.200.98'}) do
    print(ip, geoip(ip))
end

Script breaks on 165.72.200.98 :

# lua test.lua
8.8.8.8 US
lua: The lookup path does not match the data (key that doesn't exist, array index bigger than the array, expected array or map where none exists)
stack traceback:
        [C]: in function 'get'
        test.lua:6: in function 'geoip'
        test.lua:10: in main chunk
        [C]: ?
@fabled
Copy link
Owner

fabled commented May 5, 2022

You can use standard lua error handling via pcall, e.g. something like:

function geoip(ip)
    local ok, res, status = pcall(db.lookup, db, ip)
    if not ok then return nil end
    local ok, val = pcall(res.get, res, "country", "iso_code")
    if not ok then return nil end
    return val
end

Though it might make sense to add or modify the methods to not generate hard error on "not found" error, but instead return nil.

@Isma399
Copy link
Author

Isma399 commented May 6, 2022

Thank you, that works very well!
I don't event expect that you answer me so thanks again.
I've also thought to modify line82 of maxminddb.c to return nil.
But I don't know of to write that in C.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants