Skip to content

Instantly share code, notes, and snippets.

@suzuki-shunsuke
Created September 15, 2017 14:28
Show Gist options
  • Save suzuki-shunsuke/51f31512267e5ee4fcdbd439e0bfb966 to your computer and use it in GitHub Desktop.
Save suzuki-shunsuke/51f31512267e5ee4fcdbd439e0bfb966 to your computer and use it in GitHub Desktop.
runtimeエラーを処理する汎用的なコード。
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
}
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