golang(gin) globally unified exception handling and unified return to json
Define Recover Middleware
package handler import ( "awesomeProject/Result" "/gin-gonic/gin" "log" "net/http" "runtime/debug" ) func Recover(c *) { defer func() { if r := recover(); r != nil { //Print error stack information ("panic: %v\n", r) () //Encapsulated general json return //(, (errorToString(r))) //It is not the focus of this example, so use the following code instead (, { "code": "1", "msg": errorToString(r), "data": nil, }) // Terminate subsequent interface calls. If you do not add recovery to the exception, the subsequent code in the interface will continue to be executed after the recovery is reached. () } }() //After loading defer recover, continue to follow-up interface calls () } // Recover error, turn stringfunc errorToString(r interface{}) string { switch v := r.(type) { case error: return () default: return r.(string) } }
Using Recover Middleware
func main() { router := () //Note that Recover should be placed first and loaded //If not, middleware or routes before recovery will not be intercepted //The principle of the program is: //1. Request in and execute recovery //2. Program exception, throw panic //Catched by recover, return exception information, and Abort, terminate this request () ("/ping", func(c *) { // Unintentionally throw panic var slice = []int{1, 2, 3, 4, 5} slice[6] = 6 }) (":8080") // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080") }
Exception handling problem in golang
If there is a problem during the program running, you can handle the exception by throwing and catching exceptions. In golang, the interface of the exception is error:
type error interface { Error() string }
Therefore, as long as a structure implements the Error() string method, the error interface is implemented:
type MyError struct { } func (err *MyError)Error() string{ return "this is MyError" }
In golang, panic can be used to throw exceptions and recover to catch exceptions. If the exception is not handled, the entire program will eventually exit
In addition, **Catching exceptions must be captured in defer, otherwise, catch exception recovery will not work**
type MyError struct { } func (err *MyError)Error() string{ return "this is MyError" } func PanicError() { ("panic error") panic(MyError{}) } func main() { defer func(){ if err := recover() ; err != nil { ("catch error ",err) } }() PanicError() }
The defer mechanism is somewhat similar to the final statement block in java
Multiple defer statements in go execute in the opposite order of defers. It can be understood that defers are placed in a first-in and later-out queue.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.