---
title: Abort with Status for Errors
impact: MEDIUM
impactDescription: ensures middleware chain is interrupted and consistent response is sent
tags: gin, go, error-handling, quality
---

## Abort with Status for Errors

When a fatal error occurs in a Gin handler or middleware (e.g., auth failure, validation error), use `c.AbortWithStatusJSON` or `c.Abort()` to stop the execution of subsequent handlers in the chain.

**Incorrect (not aborting or only partial return):**

```go
func AuthMiddleware(c *gin.Context) {
    token := c.GetHeader("Authorization")
    if token == "" {
        c.JSON(401, gin.H{"error": "unauthorized"})
        // MISSING c.Abort()! Subsequent handlers WILL execute.
        return 
    }
}
```

**Correct (using AbortWithStatusJSON):**

```go
func AuthMiddleware(c *gin.Context) {
    if c.GetHeader("Authorization") == "" {
        c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
        return
    }
}

func Handler(c *gin.Context) {
    if err := someFunc(); err != nil {
        c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
        return
    }
}
```

**Benefits:**
- Prevents security bypasses in middleware
- Consistent error response pattern
- Guarantees that only one response is sent to the client

**Tools:** Gin
