Go-micro exception capture

In the Go-Micro service layer, add an exception catching mechanism and send an alarm. This article provides only one way to catch exceptions: by adding a Handler.

1. Inject interceptors

At initialization, add an exception catch Handler. Part of the code

.// Initialize the service
config.Service = grpc.NewService(
	micro.Name("MyService"), micro.Address(...) .// Add exception interception
	micro.WrapHandler(utils.WxErrorHandler()),
)
...
Copy the code

2. The interceptor

utils |—errorHandler.go

/** * @description: exception interceptor * @return server.handlerWrapper */
func WxErrorHandler(a) server.HandlerWrapper {
	return func(h server.HandlerFunc) server.HandlerFunc {
		return func(ctx context.Context, req server.Request, rsp interface{}) error {
			defer func(a) {
				// If the signal is caused by a crash, send an alarm
				err := recover(a)iferr ! =nil {
				// post-capture processing
					errorMsg := PanicTrace(1)... }} ()return h(ctx, req, rsp)
		}
	}
}

/** * @description: Get the current stack information * @param KB size * @return string Stack information */
func PanicTrace(kb int) string {
	s := []byte("/src/runtime/panic.go")
	e := []byte("\ngoroutine ")
	line := []byte("\n")
	stack := make([]byte, kb<<10) //4KB
	length := runtime.Stack(stack, true)
	start := bytes.Index(stack, s)
	stack = stack[start:length]
	start = bytes.Index(stack, line) + 1
	stack = stack[start:]
	end := bytes.LastIndex(stack, line)
	ifend ! =- 1 {
		stack = stack[:end]
	}
	end = bytes.Index(stack, e)
	ifend ! =- 1 {
		stack = stack[:end]
	}
	stack = bytes.TrimRight(stack, "\n")
	return string(stack)
}
Copy the code