Skip to content
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

Goのpanic,recover周りについて #70

Open
awakia opened this issue Jan 20, 2018 · 1 comment
Open

Goのpanic,recover周りについて #70

awakia opened this issue Jan 20, 2018 · 1 comment

Comments

@awakia
Copy link
Owner

awakia commented Jan 20, 2018

この記事が秀逸
https://blog.golang.org/defer-panic-and-recover
panic, recover, deferの挙動の詳細が書いてある。

後は別件で、goroutineの中でのpanicはhandle出来ない。もちろんそのgoroutine内でdeferしてrecoverすれば大丈夫

@awakia
Copy link
Owner Author

awakia commented Jan 20, 2018

ginのRecoveryミドルウェアのコード。
panicを500エラーになるように変えている

// Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.
func Recovery() HandlerFunc {
	return RecoveryWithWriter(DefaultErrorWriter)
}

// RecoveryWithWriter returns a middleware for a given writer that recovers from any panics and writes a 500 if there was one.
func RecoveryWithWriter(out io.Writer) HandlerFunc {
	var logger *log.Logger
	if out != nil {
		logger = log.New(out, "\n\n\x1b[31m", log.LstdFlags)
	}
	return func(c *Context) {
		defer func() {
			if err := recover(); err != nil {
				if logger != nil {
					stack := stack(3)
					httprequest, _ := httputil.DumpRequest(c.Request, false)
					logger.Printf("[Recovery] panic recovered:\n%s\n%s\n%s%s", string(httprequest), err, stack, reset)
				}
				c.AbortWithStatus(500)
			}
		}()
		c.Next()
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant