Created
September 15, 2017 14:28
-
-
Save suzuki-shunsuke/51f31512267e5ee4fcdbd439e0bfb966 to your computer and use it in GitHub Desktop.
runtimeエラーを処理する汎用的なコード。
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
package models | |
type RuntimeError interface { | |
Param() interface{} // runtimeエラーが起こった祭のpanic()の引数を取得 | |
Error() string | |
} | |
type runtimeErrorImpl struct { | |
data struct { | |
param interface{} | |
} | |
} | |
func (e runtimeErrorImpl) Param() interface{} { | |
return e.data.param | |
} | |
func (e runtimeErrorImpl) Error() string { | |
return "runtime error" | |
} | |
// ランタイムエラーをerrorオブジェクトに変換 | |
func NewRuntimeError(p interface{}) RuntimeError { | |
e := runtimeErrorImpl{} | |
e.data.param = p | |
return e | |
} |
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
package controllers | |
import ( | |
"fmt" | |
"net/http" | |
"github.com/labstack/echo" | |
"github.com/suzuki-shunsuke/hello-echo/models" | |
) | |
func CheckHealth(c echo.Context) (e error) { // 名前付きの戻り値を宣言 | |
defer func() { | |
p := recover() | |
if p != nil { | |
// deferで元の関数の戻り値に代入 | |
e = models.NewRuntimeError(p) | |
} | |
}() | |
var a *int | |
fmt.Println(*a) // panicが起こる | |
return c.JSON(http.StatusOK, map[string]string{"message": "ok"}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment