How does Kong detect connection timeout?

2k Views Asked by At

Currently, whenever an upstream service is down, kong will throw "{"message":"failure to get a peer from the ring-balancer"}"

I am trying to create a custom plugin that detects the connection time out and return a customized message to the client, the blocker I am facing right now is writing lua codes in my custom plugin to detect the timeout. I have tried using

if(kong.response.get_source() == "error")

but that does not seem to detect timeout either.

Does anyone have any idea what I should do to detect connection timeout in when writing a custom kong plugin?

1

There are 1 best solutions below

2
On

Sorry, I didn't catch you. Because I don't know what your function will return

If kong.response.get_source() returns a string {"message":"failure to get a peer from the ring-balancer"}

You need to use the JSON library to parse it.

local json = require("json")
local res = json.deceode(kong.response.get_source())
if res.message == "xxx" then

end

But your message is a little long. You can add a new key-value to the JSON string to represent the state.

For example:"{"status":"error","message":"failure to get a peer from the ring-balancer"}"

Then you can write code like this.

local json = require("json")
local res = json.deceode(kong.response.get_source())
if res.status == "error" then

end

I just looked at the Kong API Docs.

I find that the return value of kong.response.get_source() is HTTP status code, such as 200/500.

You can try print(kong.response.get_source()) and see the results.