-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(api): implement error handling middleware
- Loading branch information
1 parent
377a6f5
commit 51d7e40
Showing
4 changed files
with
60 additions
and
2 deletions.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
package mid | ||
|
||
import ( | ||
"context" | ||
"net/http" | ||
|
||
"github.com/youngjun827/thoughts/business/web/v1/response" | ||
"github.com/youngjun827/thoughts/foundation/logger" | ||
"github.com/youngjun827/thoughts/foundation/web" | ||
) | ||
|
||
func Errors(log *logger.Logger) web.Middleware { | ||
m := func(handler web.Handler) web.Handler { | ||
h := func(ctx context.Context, w http.ResponseWriter, r *http.Request) error { | ||
if err := handler(ctx, w, r); err != nil { | ||
log.Error(ctx, "message", "msg", err) | ||
|
||
var er response.ErrorDocument | ||
var status int | ||
|
||
switch { | ||
case response.IsError(err): | ||
reqErr := response.GetError(err) | ||
er = response.ErrorDocument{ | ||
Error: reqErr.Error(), | ||
} | ||
status = reqErr.Status | ||
|
||
default: | ||
er = response.ErrorDocument{ | ||
Error: http.StatusText(http.StatusInternalServerError), | ||
} | ||
status = http.StatusInternalServerError | ||
} | ||
|
||
if err := web.Respond(ctx, w, er, status); err != nil { | ||
return err | ||
} | ||
|
||
if web.IsShutdown(err) { | ||
return err | ||
} | ||
} | ||
|
||
return nil | ||
} | ||
|
||
return h | ||
} | ||
|
||
return m | ||
} |
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