Add CustomRecovery builtin middleware (#2322)
* Add CustomRecovery and CustomRecoveryWithWriter methods * add CustomRecovery example to README * add test for CustomRecovery * support RecoveryWithWriter(io.Writer, ...RecoveryFunc)
This commit is contained in:
		
							
								
								
									
										33
									
								
								README.md
									
									
									
									
									
								
							
							
						
						
									
										33
									
								
								README.md
									
									
									
									
									
								
							@ -496,6 +496,39 @@ func main() {
 | 
			
		||||
}
 | 
			
		||||
```
 | 
			
		||||
 | 
			
		||||
### Custom Recovery behavior
 | 
			
		||||
```go
 | 
			
		||||
func main() {
 | 
			
		||||
	// Creates a router without any middleware by default
 | 
			
		||||
	r := gin.New()
 | 
			
		||||
 | 
			
		||||
	// Global middleware
 | 
			
		||||
	// Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release.
 | 
			
		||||
	// By default gin.DefaultWriter = os.Stdout
 | 
			
		||||
	r.Use(gin.Logger())
 | 
			
		||||
 | 
			
		||||
	// Recovery middleware recovers from any panics and writes a 500 if there was one.
 | 
			
		||||
	r.Use(gin.CustomRecovery(func(c *gin.Context, recovered interface{}) {
 | 
			
		||||
		if err, ok := recovered.(string); ok {
 | 
			
		||||
			c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err))
 | 
			
		||||
		}
 | 
			
		||||
		c.AbortWithStatus(http.StatusInternalServerError)
 | 
			
		||||
	}))
 | 
			
		||||
 | 
			
		||||
	r.GET("/panic", func(c *gin.Context) {
 | 
			
		||||
		// panic with a string -- the custom middleware could save this to a database or report it to the user
 | 
			
		||||
		panic("foo")
 | 
			
		||||
	})
 | 
			
		||||
 | 
			
		||||
	r.GET("/", func(c *gin.Context) {
 | 
			
		||||
		c.String(http.StatusOK, "ohai")
 | 
			
		||||
	})
 | 
			
		||||
 | 
			
		||||
	// Listen and serve on 0.0.0.0:8080
 | 
			
		||||
	r.Run(":8080")
 | 
			
		||||
}
 | 
			
		||||
```
 | 
			
		||||
 | 
			
		||||
### How to write log file
 | 
			
		||||
```go
 | 
			
		||||
func main() {
 | 
			
		||||
 | 
			
		||||
		Reference in New Issue
	
	Block a user