| 
									
										
										
										
											2024-01-17 23:17:21 -06:00
										 |  |  | package handler | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | import "github.com/gin-gonic/gin" | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-01-22 20:08:03 -06:00
										 |  |  | // This is essentially the same as [gin.HandlerFunc], but allows returning | 
					
						
							|  |  |  | // an error. This allows for the more idiomatic use: | 
					
						
							|  |  |  | // | 
					
						
							|  |  |  | //	func UserHandler (c *gin.Context) error { | 
					
						
							|  |  |  | //	    user, err := db.GetUser(c.Get("user")) | 
					
						
							|  |  |  | //	    if err != nil { | 
					
						
							|  |  |  | //	        return err | 
					
						
							|  |  |  | //	    } | 
					
						
							|  |  |  | //	    c.JSON(200, user) | 
					
						
							|  |  |  | //	} | 
					
						
							| 
									
										
										
										
											2024-01-17 23:17:21 -06:00
										 |  |  | type HandlerWithError func(c *gin.Context) error | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-01-22 20:08:03 -06:00
										 |  |  | // Allows you to actually use a [HandlerWithError] as a [gin.HandlerFunc]. | 
					
						
							|  |  |  | // If an error is returned, it adds it to the context with c.Error(err). | 
					
						
							|  |  |  | // This needs to be handled with a middleware, such as [ErrorMiddleware] | 
					
						
							|  |  |  | // | 
					
						
							|  |  |  | // Usage: | 
					
						
							|  |  |  | // | 
					
						
							|  |  |  | //	c.GET("/user", HandlerWithErrorWrapper(UserHandler)) | 
					
						
							| 
									
										
										
										
											2024-01-17 23:17:21 -06:00
										 |  |  | func HandlerWithErrorWrapper(h HandlerWithError) gin.HandlerFunc { | 
					
						
							|  |  |  | 	return func(c *gin.Context) { | 
					
						
							|  |  |  | 		err := h(c) | 
					
						
							|  |  |  | 		if err != nil { | 
					
						
							| 
									
										
										
										
											2024-02-07 08:41:54 -06:00
										 |  |  | 			// We shouldn't process more handlers if there was an error | 
					
						
							|  |  |  | 			c.Abort() | 
					
						
							| 
									
										
										
										
											2024-01-17 23:17:21 -06:00
										 |  |  | 			c.Error(err) | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | } |