The Wayback Machine - https://web.archive.org/web/20210816120924/https://github.com/tal-tech/go-zero/issues/890
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

是否有异常恢复中间件呢? #890

Open
langbin522 opened this issue Aug 10, 2021 · 1 comment
Open

是否有异常恢复中间件呢? #890

langbin522 opened this issue Aug 10, 2021 · 1 comment

Comments

@langbin522
Copy link

@langbin522 langbin522 commented Aug 10, 2021

默认了异常恢复直接是500状态,空白页。能否让我们来做这个呢

@kevwan
Copy link
Contributor

@kevwan kevwan commented Aug 14, 2021

下面的代码可以做到

package main

import (
	"net/http"

	"github.com/tal-tech/go-zero/core/logx"
	"github.com/tal-tech/go-zero/core/service"
	"github.com/tal-tech/go-zero/rest"
)

type codedResponseWriter struct {
	w    http.ResponseWriter
	r    *http.Request
	code int
}

func (w *codedResponseWriter) Flush() {
	if flusher, ok := w.w.(http.Flusher); ok {
		flusher.Flush()
	}
}

func (w *codedResponseWriter) Header() http.Header {
	return w.w.Header()
}

func (w *codedResponseWriter) Write(bytes []byte) (int, error) {
	if w.code == http.StatusInternalServerError {
		w.w.Write([]byte("oops"))
	}
	return w.w.Write(bytes)
}

func (w *codedResponseWriter) WriteHeader(code int) {
	w.w.WriteHeader(code)
	w.code = code
	if w.code == http.StatusInternalServerError {
		w.w.Write([]byte("oops"))
	}
}

func main() {
	srv := rest.MustNewServer(rest.RestConf{
		ServiceConf: service.ServiceConf{
			Name: "adhoc",
			Log: logx.LogConf{
				Mode: "console",
			},
		},
		Host: "127.0.0.1",
		Port: 8888,
	})
	srv.AddRoute(rest.Route{
		Method: http.MethodGet,
		Path:   "/panic",
		Handler: func(w http.ResponseWriter, r *http.Request) {
			panic("bad things happen")
		},
	})
	srv.AddRoute(rest.Route{
		Method: http.MethodGet,
		Path:   "/error",
		Handler: func(w http.ResponseWriter, r *http.Request) {
			w.WriteHeader(http.StatusInternalServerError)
		},
	})
	srv.Use(func(next http.HandlerFunc) http.HandlerFunc {
		return func(w http.ResponseWriter, r *http.Request) {
			defer func() {
				if p := recover(); p != nil {
					w.WriteHeader(http.StatusInternalServerError)
					w.Write([]byte("oops"))
				}
			}()

			cw := &codedResponseWriter{
				w: w,
				r: r,
			}
			next(cw, r)
		}
	})
	defer srv.Stop()
	srv.Start()
}

详细代码见这里
https://github.com/kevwan/zero-issues/blob/main/890/main.go

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

Successfully merging a pull request may close this issue.

None yet
2 participants