-
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.
Merge pull request #7 from naohito-T/feature/error-handler
Feature/error handler
- Loading branch information
Showing
22 changed files
with
205 additions
and
68 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 |
---|---|---|
@@ -1 +1 @@ | ||
1.21.1 | ||
1.21.0 |
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
Empty file.
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,14 @@ | ||
package configs | ||
|
||
// type MyType intと宣言するDefined type | ||
// 以前はNamed typeと言っていたが、Go1.11からDefined typeと呼ぶようになった | ||
// type MyType = intと宣言するType alias | ||
// see: https://zenn.dev/bluetree/articles/9d52842dff35cc | ||
// go 1.19から導入された型エイリアス(これで推測され、string()などのキャストが不要になる) | ||
type path = string | ||
|
||
const ( | ||
Health path = "/health" | ||
GetShortURL path = "/api/v1/urls/:shortUrl" | ||
CreateShortURL path = "/api/v1/urls" | ||
) |
File renamed without changes.
File renamed without changes.
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,4 @@ | ||
#!/bin/bash | ||
|
||
# 将来的には開発ツールもdocker内で実行するようにする。 | ||
docker run -t --rm -v $(pwd):/app -w /app golangci/golangci-lint:v1.57.2 golangci-lint run -v |
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,29 @@ | ||
package customerror | ||
|
||
// ApplicationError はアプリケーション特有のエラー情報を保持する基本構造体です。 | ||
type ApplicationErrorCode struct { | ||
// StatusCode(JSON parseでは構造体省略) | ||
Status int `json:"-"` | ||
// Code はエラーコードを表します。 | ||
Code string `json:"code"` | ||
// Message はエラーメッセージを表します。 | ||
Message string `json:"message"` | ||
} | ||
|
||
var ( | ||
WrongEmailVerificationCode ApplicationErrorCode = ApplicationErrorCode{ | ||
Code: "WRONG_EMAIL_VERIFICATION_ERROR", | ||
Message: "Wrong email verification code", | ||
} | ||
|
||
// Unknown Error: システムがエラーの原因を特定できないか、エラーの種類が分類されていない場合に使用する。 | ||
UnknownCode ApplicationErrorCode = ApplicationErrorCode{ | ||
Code: "unknown_error", | ||
Message: "unknown_error", | ||
} | ||
|
||
UnexpectedCode ApplicationErrorCode = ApplicationErrorCode{ | ||
Code: "unexpected_error", | ||
Message: "unexpected_error", | ||
} | ||
) |
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,59 @@ | ||
package customerror | ||
|
||
import ( | ||
"fmt" | ||
"net/http" | ||
"net/url" | ||
) | ||
|
||
// ApplicationError はアプリケーション特有のエラー情報を保持する基本構造体です。 | ||
type ApplicationError struct { | ||
// StatusCode(JSON parseでは構造体省略) | ||
Status int `json:"-"` | ||
// Code はエラーコードを表します。 | ||
Code string `json:"code"` | ||
// Message はエラーメッセージを表します。 | ||
Message string `json:"message"` | ||
} | ||
|
||
// Error メソッドは error インターフェースを実装します。 | ||
func (e *ApplicationError) Error() string { | ||
return fmt.Sprintf("Code: %s, Message: %s", e.Code, e.Message) | ||
} | ||
|
||
// WrongEmailVerificationError は特定の条件下で利用されるカスタムエラーです。 | ||
type WrongEmailVerificationError struct { | ||
ApplicationError | ||
IsTally bool | ||
IsRedirect bool | ||
RedirectQuery *url.Values | ||
} | ||
|
||
// NewWrongEmailVerificationError は WrongEmailVerificationError を生成します。 | ||
func NewWrongEmailVerificationError(isTally, isRedirect bool, redirectQuery string) *WrongEmailVerificationError { | ||
q, _ := url.ParseQuery(redirectQuery) | ||
return &WrongEmailVerificationError{ | ||
ApplicationError: ApplicationError{ | ||
Status: http.StatusBadRequest, | ||
Code: "WRONG_EMAIL_VERIFICATION_ERROR", | ||
Message: "Wrong email verification code", | ||
}, | ||
IsTally: isTally, | ||
IsRedirect: isRedirect, | ||
RedirectQuery: &q, | ||
} | ||
} | ||
|
||
// LogError はエラーのロギングを行うメソッドです。 | ||
func (e *WrongEmailVerificationError) LogError(req *http.Request) { | ||
fmt.Println("Error occurred:", e.Error(), "Query:", e.RedirectQuery.Encode()) | ||
} | ||
|
||
// Is メソッドを追加 | ||
// func (e *WrongEmailVerificationError) Is(target error) bool { | ||
// t, ok := target.(*WrongEmailVerificationError) | ||
// return ok && e.Code == t.Code | ||
// } | ||
|
||
// WrongEmailVerificationErrorInstance は WrongEmailVerificationError のグローバルインスタンスです。 | ||
var WrongEmailVerificationErrorInstance = NewWrongEmailVerificationError(false, false, "") |
This file was deleted.
Oops, something went wrong.
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
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,16 @@ | ||
package handler | ||
|
||
import ( | ||
"net/http" | ||
|
||
"github.com/labstack/echo/v4" | ||
"github.com/naohito-T/tinyurl/backend/domain/customerror" | ||
) | ||
|
||
func HealthHandler(c echo.Context) error { | ||
a := true | ||
if a { | ||
return customerror.WrongEmailVerificationErrorInstance | ||
} | ||
return c.JSON(http.StatusOK, map[string]string{"message": "ok2"}) | ||
} |
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,11 @@ | ||
package handler | ||
|
||
import ( | ||
"net/http" | ||
|
||
"github.com/labstack/echo/v4" | ||
) | ||
|
||
func ShortURLHandler(c echo.Context) error { | ||
return c.String(http.StatusOK, "OK") | ||
} |
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 |
---|---|---|
@@ -1,30 +1,34 @@ | ||
package error | ||
|
||
// see: https://go.dev/play/p/TzZE1mdL63_1 | ||
|
||
import ( | ||
"net/http" | ||
"errors" | ||
|
||
"github.com/labstack/echo/v4" | ||
"github.com/naohito-T/tinyurl/backend/domain/customerror" | ||
) | ||
|
||
// これはGo言語における型アサーション(type assertion)の一例です。型アサーションは、インターフェースの値が特定の型を持っているかどうかをチェックし、その型の値を取り出すために使用されます。 | ||
// このコードの場合、err はエラーを表すインターフェース型です。*echo.HTTPError は echo パッケージの HTTPError 型のポインタです。この行は、err が *echo.HTTPError 型の値を持っているかをチェックし、もしそうであれば he にその値を割り当て、ok に true を設定します。err が *echo.HTTPError 型でなければ、ok は false になり、he は nil になります。 | ||
// この型アサーションを使うことで、安全に型変換を行いつつ、エラーチェックを同時に実施できます。 | ||
func CustomErrorHandler(err error, c echo.Context) { | ||
he, ok := err.(*echo.HTTPError) | ||
if !ok { | ||
he = echo.NewHTTPError(http.StatusInternalServerError, err.Error()) | ||
} | ||
|
||
c.Logger().Error("カスタムエラーに入ったよ") | ||
// ロギング | ||
c.Logger().Error(err) | ||
// c.Logger().Error(err) | ||
appErr := buildError(err, c) | ||
c.JSON(appErr.Status, map[string]string{"code": appErr.Code, "message": appErr.Message}) | ||
} | ||
|
||
// エラータイプによって条件分岐 | ||
if he.Code == http.StatusNotFound { | ||
// リダイレクトを行う例 | ||
if err := c.Redirect(http.StatusTemporaryRedirect, "/some-fallback-url"); err != nil { | ||
c.Logger().Error(err) | ||
} | ||
} else { | ||
// エラーレスポンスを送信する例 | ||
if err := c.JSON(he.Code, map[string]string{"message": he.Message.(string)}); err != nil { | ||
c.Logger().Error(err) | ||
} | ||
func buildError(err error, c echo.Context) *customerror.ApplicationError { | ||
appErr := customerror.ApplicationError{ | ||
Status: customerror.UnexpectedCode.Status, | ||
Code: customerror.UnexpectedCode.Code, | ||
Message: customerror.UnexpectedCode.Message, | ||
} | ||
if errors.Is(err, customerror.WrongEmailVerificationErrorInstance) { | ||
c.Logger().Error("これがWrongEmailVerificationErrorアプリケーションエラー") | ||
// return &customerror.ApplicationError{} | ||
} | ||
return &appErr | ||
} |
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 |
---|---|---|
@@ -1,14 +1,24 @@ | ||
package middleware | ||
|
||
// see: https://echo.labstack.com/docs/category/middleware | ||
|
||
import ( | ||
"github.com/labstack/echo/v4" | ||
"github.com/labstack/echo/v4/middleware" | ||
"github.com/naohito-T/tinyurl/backend/internal/rest/middleware/accesslog" | ||
"github.com/naohito-T/tinyurl/backend/internal/rest/middleware/error" | ||
|
||
// "github.com/naohito-T/tinyurl/backend/internal/rest/middleware/accesslog" | ||
ehandler "github.com/naohito-T/tinyurl/backend/internal/rest/middleware/error" | ||
) | ||
|
||
// loggerの考え方 | ||
// https://yuya-hirooka.hatenablog.com/entry/2021/10/15/123607 | ||
func CustomMiddleware(e *echo.Echo) { | ||
e.Use(accesslog.AccessLog()) | ||
e.HTTPErrorHandler = error.CustomErrorHandler | ||
// e.Use(accesslog.AccessLog()) | ||
// expect this handler is used as fallback unless a more specific is present | ||
e.Use(middleware.Recover()) | ||
// これでechoのloggerを操作できる。 | ||
// e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{ | ||
// Format: "time=${time_rfc3339_nano}, method=${method}, uri=${uri}, status=${status}\n", | ||
// })) | ||
e.HTTPErrorHandler = ehandler.CustomErrorHandler | ||
} |
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,11 @@ | ||
package security | ||
|
||
import ( | ||
"github.com/labstack/echo/v4" | ||
) | ||
|
||
func AttachSecurity(e *echo.Echo) { | ||
// サーバー起動時のバナーを非表示にする | ||
e.HideBanner = true | ||
e.HidePort = true | ||
} |
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 was deleted.
Oops, something went wrong.
Oops, something went wrong.