Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/ARCHITECTURE_OVERVIEW.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ UserCreatedEventHandler → gửi email welcome
- Validation, Logging, Authorization, etc.

```csharp
Request → ValidationBehavior → AuthorizationBehavior → Handler → Response
Request → ValidationBehavior → Handler → Response
```

## 📂 **FOLDERS QUAN TRỌNG NHẤT**
Expand Down
33 changes: 4 additions & 29 deletions docs/BEHAVIORS_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

### **Behaviors = Middleware cho Commands/Queries**
```
Request → ValidationBehavior → AuthorizationBehavior → LoggingBehavior → Handler → Response
Request → ValidationBehavior → LoggingBehavior → Handler → Response
```
Comment on lines +9 to 10
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Docs still reference AuthorizationBehavior/IAuthorizedRequest despite removal

The guide is internally inconsistent and out of sync with the current pipeline:

  • The top pipeline (line 9) shows Request → ValidationBehavior → LoggingBehavior → Handler → Response, but the detailed pipeline (lines 115–143) still includes AuthorizationBehavior.
  • The “Authorization” usage section (lines 161–172) still documents IAuthorizedRequest and AuthorizationRequirement.
  • The comparison table (lines 195–201) advertises “Centralized authorization” via behaviors.

Now that authorization is handled differently (e.g., via filters/JWT policies), this doc should be updated to remove or rewrite these sections so it matches the actual behavior.

Also applies to: 115-143, 161-172, 195-201

🤖 Prompt for AI Agents
In docs/BEHAVIORS_GUIDE.md around lines 9–10, 115–143, 161–172, and 195–201, the
guide still references AuthorizationBehavior, IAuthorizedRequest, and
AuthorizationRequirement even though authorization has been moved to filters/JWT
policies; remove or rewrite all mentions of AuthorizationBehavior and
IAuthorizedRequest, update the top pipeline diagram to match the actual pipeline
(e.g., Request → ValidationBehavior → LoggingBehavior → Handler → Response),
update the detailed pipeline section to remove AuthorizationBehavior, replace
the “Authorization” usage section with a short description of how authorization
is now handled (filters, JWT policy enforcement, and links to relevant docs or
code), and update the comparison table to remove or reword the “Centralized
authorization” claim so the document is consistent with current implementation.


**Mỗi behavior là 1 layer xử lý cross-cutting concerns trước/sau khi handler chạy.**
Expand Down Expand Up @@ -35,32 +35,7 @@ public class CreateUserCommandValidator : AbstractValidator<CreateUserCommand>
// Nếu fail → throw ValidationException
```

### **2. 🔐 AuthorizationBehavior**
- **Mục đích**: Kiểm tra quyền truy cập
- **Khi nào chạy**: Sau validation, trước handler
- **Input**: IAuthorizedRequest interface
- **Output**: Throw UnauthorizedException/ForbiddenException

```csharp
// Command yêu cầu authorization
public record CreateUserCommand : ICommand<Result<CreateUserResponse>>,
IAuthorizedRequest
{
public AuthorizationRequirement AuthorizationRequirement => new()
{
Roles = ["Admin"], // Cần role Admin
Permissions = ["users.create"], // Cần permission users.create
RequireAuthentication = true
};
}

// AuthorizationBehavior sẽ check:
// - User có authenticated không?
// - User có role Admin không?
// - User có permission users.create không?
```

### **3. 📊 LoggingBehavior**
### **2. 📊 LoggingBehavior**
- **Mục đích**: Log tất cả requests/responses
- **Khi nào chạy**: Bao quanh handler (before + after)
- **Input**: Request name
Expand Down Expand Up @@ -92,7 +67,7 @@ public record CreateUserCommand : ICommand<Result<CreateUserResponse>>,

```csharp
// Query với caching
public record GetUserByIdQuery(Guid UserId) : IQuery<UserResponse>,
public record GetUserByIdQuery(Guid UserId) : IQuery<UserResponse>,
ICacheableQuery
{
public string CacheKey => $"user-{UserId}";
Expand All @@ -104,7 +79,7 @@ public record GetUserByIdQuery(Guid UserId) : IQuery<UserResponse>,
// 2. Nếu không → execute handler → cache result → return
```

### **6. 🔄 TransactionBehavior**
### **6. 💳 TransactionBehavior**
- **Mục đích**: Wrap commands trong database transaction
- **Khi nào chạy**: Chỉ cho commands implement ITransactionalCommand
- **Rollback**: Automatic nếu có exception
Expand Down
40 changes: 1 addition & 39 deletions docs/EXCEPTION_GUIDELINES.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ Exception
├── NotFoundException
├── UnauthorizedException
├── BusinessRuleViolationException
├── RequestProcessingException
└── DomainEventDispatchException
```

Expand Down Expand Up @@ -203,28 +202,6 @@ if (!user.HasRole("Admin"))
throw new UnauthorizedException("Access denied", "Admin");
```

#### **RequestProcessingException**
```csharp
namespace Application.Common.Exceptions;

public sealed class RequestProcessingException : Exception
{
public RequestProcessingException(string message) : base(message)
{
}

public RequestProcessingException(string message, Exception innerException)
: base(message, innerException)
{
}
}

// Usage in MediatR behaviors
catch (Exception ex)
{
throw new RequestProcessingException($"Request {requestName} failed after {duration}ms", ex);
}
```

### **Infrastructure Layer Exceptions**

Expand Down Expand Up @@ -307,8 +284,6 @@ throw new UnauthorizedException("Insufficient permissions");
// ✅ Use for not found
throw new NotFoundException("User", userId);

// ✅ Use for request processing
throw new RequestProcessingException("Command processing failed", ex);

// ❌ Don't use low-level exceptions
// throw new SqlException(...); // TOO LOW LEVEL
Expand Down Expand Up @@ -472,7 +447,7 @@ public async Task<User> CreateUserAsync(CreateUserCommand command)
}
catch (Exception ex)
{
throw new RequestProcessingException("Failed to create user", ex);
throw; // Re-throw or handle appropriately
}
}

Expand Down Expand Up @@ -515,11 +490,6 @@ public async Task<IActionResult> CreateUser(CreateUserCommand command)
{
return BadRequest(new { rule = ex.RuleName, message = ex.Message });
}
catch (RequestProcessingException ex)
{
logger.LogError(ex, "Failed to process create user request");
return StatusCode(500, new { message = "Internal server error" });
}
}
```

Expand Down Expand Up @@ -565,11 +535,6 @@ public class GlobalExceptionMiddleware
Message = businessEx.Message,
Details = new { Rule = businessEx.RuleName }
},
RequestProcessingException requestEx => new ApiResponse
{
StatusCode = 500,
Message = "Request processing failed"
},
_ => new ApiResponse
{
StatusCode = 500,
Expand Down Expand Up @@ -607,8 +572,6 @@ Exception occurred?
│ ├── Database → DataPersistenceException
│ ├── Event dispatch → DomainEventDispatchException
│ └── External service → ExternalServiceException
└── Is it request processing failure?
└── Pipeline error → RequestProcessingException
```

---
Expand All @@ -626,7 +589,6 @@ Exception occurred?
| Entity not found | `NotFoundException` | Application |
| Database operation failure | `DataPersistenceException` | Infrastructure |
| Event dispatch failure | `DomainEventDispatchException` | Infrastructure |
| Request processing failure | `RequestProcessingException` | Application |

---

Expand Down
218 changes: 0 additions & 218 deletions file_tree.md

This file was deleted.

Loading