-
Notifications
You must be signed in to change notification settings - Fork 2
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
SCT-156 Build: ErrorHandlerMiddleware pattern in Bean framework #28
Merged
Merged
Changes from 2 commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
109 changes: 109 additions & 0 deletions
109
internal/project/framework/internals/error/error_middleware.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,109 @@ | ||
/**#bean*/ /*#bean.replace({{ .Copyright }})**/ | ||
|
||
package error | ||
|
||
import ( | ||
/**#bean*/ | ||
"demo/framework/internals/sentry" | ||
/*#bean.replace("{{ .PkgPath }}/framework/internals/sentry")**/ | ||
/**#bean*/ | ||
"demo/framework/internals/validator" | ||
/*#bean.replace("{{ .PkgPath }}/framework/internals/validator")**/ | ||
"github.com/labstack/echo/v4" | ||
"net/http" | ||
"strings" | ||
) | ||
|
||
// return value: bool is true when HandlerMiddleware match the error,otherwise false | ||
// return value: error will be sent to sentry if not nil | ||
|
||
type ErrorHandlerMiddleware func(err error, c echo.Context) (bool, error) | ||
|
||
func ErrorHandlerChain(middlewares ...ErrorHandlerMiddleware) echo.HTTPErrorHandler { | ||
return func(err error, c echo.Context) { | ||
|
||
if c.Response().Committed { | ||
return | ||
} | ||
|
||
for _, middleware := range middlewares { | ||
catched, e := middleware(err, c) | ||
if e != nil { | ||
sentry.PushData(c, e, nil, true) | ||
} | ||
if catched { | ||
break | ||
} | ||
} | ||
} | ||
} | ||
|
||
func ValidationErrorHanderMiddleware(e error, c echo.Context) (bool, error) { | ||
he, ok := e.(*validator.ValidationError) | ||
if !ok { | ||
return false, nil | ||
} | ||
err := c.JSON(http.StatusUnprocessableEntity, errorResp{ | ||
ErrorCode: API_DATA_VALIDATION_FAILED, | ||
Errors: he.ErrCollection(), | ||
ErrorMsg: nil, | ||
}) | ||
|
||
return ok, err | ||
} | ||
|
||
func APIErrorHanderMiddleware(e error, c echo.Context) (bool, error) { | ||
he, ok := e.(*APIError) | ||
if !ok { | ||
return false, nil | ||
} | ||
|
||
if he.HTTPStatusCode >= 404 { | ||
sentry.PushData(c, he, nil, true) | ||
} | ||
|
||
err := c.JSON(he.HTTPStatusCode, errorResp{ | ||
ErrorCode: he.GlobalErrCode, | ||
Errors: nil, | ||
ErrorMsg: he.Error(), | ||
}) | ||
|
||
return ok, err | ||
} | ||
|
||
func HTTPErrorHanderMiddleware(e error, c echo.Context) (bool, error) { | ||
he, ok := e.(*echo.HTTPError) | ||
if !ok { | ||
return false, nil | ||
} | ||
|
||
// Just in case to capture this unused type error. | ||
err := c.JSON(he.Code, errorResp{ | ||
ErrorCode: UNKNOWN_ERROR_CODE, | ||
Errors: nil, | ||
ErrorMsg: he.Message, | ||
}) | ||
|
||
return ok, err | ||
} | ||
|
||
func DefaultErrorHanderMiddleware(_ error, c echo.Context) (bool, error) { | ||
// Get Content-Type parameter from request header to identify the request content type. If the request is for | ||
// html then we should display the error in html. | ||
contentType := c.Request().Header.Get("Content-Type") | ||
|
||
if strings.ToLower(contentType) == "text/html" { | ||
err := c.HTML(http.StatusInternalServerError, "<strong>Internal server error.</strong>") | ||
return true, err | ||
} | ||
|
||
// All other panic errors. | ||
// Sentry already captured the panic and send notification in sentry-recover middleware. | ||
err := c.JSON(http.StatusInternalServerError, errorResp{ | ||
ErrorCode: INTERNAL_SERVER_ERROR, | ||
Errors: nil, | ||
ErrorMsg: nil, // TODO: Put some generic message. | ||
}) | ||
|
||
return true, err | ||
} |
153 changes: 153 additions & 0 deletions
153
internal/project/framework/internals/error/error_middleware_test.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,153 @@ | ||
/**#bean*/ /*#bean.replace({{ .Copyright }})**/ | ||
|
||
package error | ||
|
||
import ( | ||
/**#bean*/ | ||
bvalidator "demo/framework/internals/validator" | ||
/*#bean.replace(bvalidator "{{ .PkgPath }}/framework/internals/validator")**/ | ||
"encoding/json" | ||
"errors" | ||
"github.com/go-playground/validator/v10" | ||
"github.com/labstack/echo/v4" | ||
"github.com/stretchr/testify/assert" | ||
"net/http" | ||
"net/http/httptest" | ||
"testing" | ||
) | ||
|
||
func TestErrorHandlerChain(t *testing.T) { | ||
e := echo.New() | ||
e.HTTPErrorHandler = ErrorHandlerChain( | ||
FakeErrorHandlerMiddleware, | ||
ValidationErrorHanderMiddleware, | ||
APIErrorHanderMiddleware, | ||
HTTPErrorHanderMiddleware, | ||
DefaultErrorHanderMiddleware) | ||
|
||
//assert fake error | ||
fakeErr := newFakeError("fake error message") | ||
checkFakeErr := func(response *httptest.ResponseRecorder, err error) { | ||
assert.Equal(t, fakeErr, err) | ||
assert.Equal(t, http.StatusInternalServerError, response.Code) | ||
var res errorResp | ||
e := json.Unmarshal(response.Body.Bytes(), &res) | ||
assert.Nil(t, e) | ||
assert.Equal(t, ErrorCode("fakeErrorCode"), res.ErrorCode) | ||
assert.Nil(t, res.Errors) | ||
assert.Equal(t, fakeErr.Error(), res.ErrorMsg) | ||
} | ||
run(e, fakeErr, checkFakeErr) | ||
|
||
//assert api error | ||
apiErr := NewAPIError(http.StatusUnauthorized, UNAUTHORIZED_ACCESS, errors.New("UNAUTHORIZED")) | ||
checkAPIErr := func(response *httptest.ResponseRecorder, err error) { | ||
assert.Equal(t, apiErr, err) | ||
assert.Equal(t, http.StatusUnauthorized, response.Code) | ||
var res errorResp | ||
e := json.Unmarshal(response.Body.Bytes(), &res) | ||
assert.Nil(t, e) | ||
assert.Equal(t, UNAUTHORIZED_ACCESS, res.ErrorCode) | ||
assert.Nil(t, res.Errors) | ||
assert.Equal(t, apiErr.Error(), res.ErrorMsg) | ||
} | ||
run(e, apiErr, checkAPIErr) | ||
|
||
//assert validation error | ||
validationErr := &bvalidator.ValidationError{ | ||
Err: validator.ValidationErrors([]validator.FieldError{}), | ||
} | ||
checkValidationErr := func(response *httptest.ResponseRecorder, err error) { | ||
assert.Equal(t, validationErr, err) | ||
assert.Equal(t, http.StatusUnprocessableEntity, response.Code) | ||
var res errorResp | ||
e := json.Unmarshal(response.Body.Bytes(), &res) | ||
assert.Nil(t, e) | ||
assert.Equal(t, API_DATA_VALIDATION_FAILED, res.ErrorCode) | ||
assert.Nil(t, res.ErrorMsg) | ||
} | ||
run(e, validationErr, checkValidationErr) | ||
|
||
//assert http error | ||
httpErr := &echo.HTTPError{ | ||
Code: http.StatusNotFound, | ||
Message: "404 Not Found", | ||
} | ||
checkHttpErr := func(response *httptest.ResponseRecorder, err error) { | ||
assert.Equal(t, httpErr, err) | ||
assert.Equal(t, http.StatusNotFound, response.Code) | ||
var res errorResp | ||
e := json.Unmarshal(response.Body.Bytes(), &res) | ||
assert.Nil(t, e) | ||
assert.Equal(t, UNKNOWN_ERROR_CODE, res.ErrorCode) | ||
assert.Nil(t, res.Errors) | ||
assert.Equal(t, httpErr.Message, res.ErrorMsg) | ||
} | ||
run(e, httpErr, checkHttpErr) | ||
|
||
//assert default error | ||
defaultErr := errors.New("default error") | ||
checkDefaultErr := func(response *httptest.ResponseRecorder, err error) { | ||
assert.Equal(t, defaultErr, err) | ||
assert.Equal(t, http.StatusInternalServerError, response.Code) | ||
var res errorResp | ||
e := json.Unmarshal(response.Body.Bytes(), &res) | ||
assert.Equal(t, http.StatusInternalServerError, response.Code) | ||
assert.Nil(t, e) | ||
assert.Equal(t, INTERNAL_SERVER_ERROR, res.ErrorCode) | ||
assert.Nil(t, res.Errors) | ||
assert.Nil(t, res.ErrorMsg) | ||
} | ||
run(e, defaultErr, checkDefaultErr) | ||
} | ||
|
||
func FakeErrorHandlerMiddleware(e error, c echo.Context) (bool, error) { | ||
he, ok := e.(*fakeError) | ||
if !ok { | ||
return false, nil | ||
} | ||
|
||
err := c.JSON(http.StatusInternalServerError, errorResp{ | ||
ErrorCode: "fakeErrorCode", | ||
Errors: nil, | ||
ErrorMsg: he.Error(), | ||
}) | ||
|
||
return ok, err | ||
} | ||
|
||
func run(e *echo.Echo, | ||
err error, | ||
assertFunc func(response *httptest.ResponseRecorder, err error), | ||
) { | ||
req := httptest.NewRequest(http.MethodGet, "/", nil) | ||
runWithRequest(e, req, err, assertFunc) | ||
} | ||
|
||
func runWithRequest(e *echo.Echo, | ||
req *http.Request, | ||
er error, | ||
assertFunc func(response *httptest.ResponseRecorder, err error), | ||
) { | ||
rec := httptest.NewRecorder() | ||
c := e.NewContext(req, rec) | ||
err := func(c echo.Context) error { | ||
return er | ||
}(c) | ||
e.HTTPErrorHandler(err, c) | ||
assertFunc(rec, err) | ||
} | ||
|
||
type fakeError struct { | ||
Message string | ||
} | ||
|
||
func (f *fakeError) Error() string { | ||
return f.Message | ||
} | ||
|
||
func newFakeError(msg string) error { | ||
return &fakeError{ | ||
Message: msg, | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
we can also use
then we don't need the concat function, right?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
yes, but it make user don't need to think about framework errorHandlers, and it make less code in
main.go