Use ErrorHandler to handle proxy error (#1310)

The router prints error no matter what error type it is.
It's useful for troubleshooting, however, it also prints
the context canceled error, which means that users abort
request before reply and its really normal nowadays. Also,
the router returns 502 if error is not nil and may confused
client if it's a timeout error.

To solve these problems, this PR adds an error handler to
reverse proxy to examine the return error and change the
status code when needed.
This commit is contained in:
Ta-Ching Chen
2019-09-28 14:22:20 +08:00
committed by GitHub
parent 81ae6f38fc
commit 71b587b58e
3 changed files with 123 additions and 3 deletions
+25
View File
@@ -17,6 +17,8 @@ limitations under the License.
package router
import (
"context"
"errors"
"log"
"net/http"
"net/http/httptest"
@@ -24,6 +26,7 @@ import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"go.uber.org/zap"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@@ -90,3 +93,25 @@ func TestFunctionProxying(t *testing.T) {
testRequest(fhURL, testResponseString)
}
func TestProxyErrorHandler(t *testing.T) {
logger, err := zap.NewDevelopment()
assert.Nil(t, err)
errHandler := getProxyErrorHandler(logger, nil)
req, err := http.NewRequest("GET", "http://foobar.com", nil)
assert.Nil(t, err)
req.Header.Set("foo", "bar")
respRecorder := httptest.NewRecorder()
errHandler(respRecorder, req, context.Canceled)
assert.Equal(t, 499, respRecorder.Code)
respRecorder = httptest.NewRecorder()
errHandler(respRecorder, req, context.DeadlineExceeded)
assert.Equal(t, http.StatusGatewayTimeout, respRecorder.Code)
respRecorder = httptest.NewRecorder()
errHandler(respRecorder, req, errors.New("dummy"))
assert.Equal(t, http.StatusBadGateway, respRecorder.Code)
}