In progress
This commit is contained in:
@@ -23,7 +23,7 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="MediatR" Version="11.1.0" />
|
||||
<PackageReference Include="MediatR" Version="13.1.0" />
|
||||
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="11.10.0" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
190
colaflow-api/src/ColaFlow.API/Controllers/StoriesController.cs
Normal file
190
colaflow-api/src/ColaFlow.API/Controllers/StoriesController.cs
Normal file
@@ -0,0 +1,190 @@
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
|
||||
using ColaFlow.Modules.ProjectManagement.Application.Commands.CreateStory;
|
||||
using ColaFlow.Modules.ProjectManagement.Application.Commands.UpdateStory;
|
||||
using ColaFlow.Modules.ProjectManagement.Application.Commands.DeleteStory;
|
||||
using ColaFlow.Modules.ProjectManagement.Application.Commands.AssignStory;
|
||||
using ColaFlow.Modules.ProjectManagement.Application.Queries.GetStoryById;
|
||||
using ColaFlow.Modules.ProjectManagement.Application.Queries.GetStoriesByEpicId;
|
||||
using ColaFlow.Modules.ProjectManagement.Application.Queries.GetStoriesByProjectId;
|
||||
|
||||
namespace ColaFlow.API.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// Stories API Controller
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/v1")]
|
||||
public class StoriesController : ControllerBase
|
||||
{
|
||||
private readonly IMediator _mediator;
|
||||
|
||||
public StoriesController(IMediator mediator)
|
||||
{
|
||||
_mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get story by ID
|
||||
/// </summary>
|
||||
[HttpGet("stories/{id:guid}")]
|
||||
[ProducesResponseType(typeof(StoryDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetStory(Guid id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var query = new GetStoryByIdQuery(id);
|
||||
var result = await _mediator.Send(query, cancellationToken);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get all stories for an epic
|
||||
/// </summary>
|
||||
[HttpGet("epics/{epicId:guid}/stories")]
|
||||
[ProducesResponseType(typeof(List<StoryDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetEpicStories(Guid epicId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var query = new GetStoriesByEpicIdQuery(epicId);
|
||||
var result = await _mediator.Send(query, cancellationToken);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get all stories for a project
|
||||
/// </summary>
|
||||
[HttpGet("projects/{projectId:guid}/stories")]
|
||||
[ProducesResponseType(typeof(List<StoryDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetProjectStories(Guid projectId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var query = new GetStoriesByProjectIdQuery(projectId);
|
||||
var result = await _mediator.Send(query, cancellationToken);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create a new story
|
||||
/// </summary>
|
||||
[HttpPost("epics/{epicId:guid}/stories")]
|
||||
[ProducesResponseType(typeof(StoryDto), StatusCodes.Status201Created)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> CreateStory(
|
||||
Guid epicId,
|
||||
[FromBody] CreateStoryRequest request,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var command = new CreateStoryCommand
|
||||
{
|
||||
EpicId = epicId,
|
||||
Title = request.Title,
|
||||
Description = request.Description,
|
||||
Priority = request.Priority,
|
||||
AssigneeId = request.AssigneeId,
|
||||
EstimatedHours = request.EstimatedHours,
|
||||
CreatedBy = request.CreatedBy
|
||||
};
|
||||
|
||||
var result = await _mediator.Send(command, cancellationToken);
|
||||
return CreatedAtAction(nameof(GetStory), new { id = result.Id }, result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Update an existing story
|
||||
/// </summary>
|
||||
[HttpPut("stories/{id:guid}")]
|
||||
[ProducesResponseType(typeof(StoryDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> UpdateStory(
|
||||
Guid id,
|
||||
[FromBody] UpdateStoryRequest request,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var command = new UpdateStoryCommand
|
||||
{
|
||||
StoryId = id,
|
||||
Title = request.Title,
|
||||
Description = request.Description,
|
||||
Status = request.Status,
|
||||
Priority = request.Priority,
|
||||
AssigneeId = request.AssigneeId,
|
||||
EstimatedHours = request.EstimatedHours
|
||||
};
|
||||
|
||||
var result = await _mediator.Send(command, cancellationToken);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Delete a story
|
||||
/// </summary>
|
||||
[HttpDelete("stories/{id:guid}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> DeleteStory(Guid id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var command = new DeleteStoryCommand { StoryId = id };
|
||||
await _mediator.Send(command, cancellationToken);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Assign a story to a user
|
||||
/// </summary>
|
||||
[HttpPut("stories/{id:guid}/assign")]
|
||||
[ProducesResponseType(typeof(StoryDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> AssignStory(
|
||||
Guid id,
|
||||
[FromBody] AssignStoryRequest request,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var command = new AssignStoryCommand
|
||||
{
|
||||
StoryId = id,
|
||||
AssigneeId = request.AssigneeId
|
||||
};
|
||||
|
||||
var result = await _mediator.Send(command, cancellationToken);
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Request model for creating a story
|
||||
/// </summary>
|
||||
public record CreateStoryRequest
|
||||
{
|
||||
public string Title { get; init; } = string.Empty;
|
||||
public string Description { get; init; } = string.Empty;
|
||||
public string Priority { get; init; } = "Medium";
|
||||
public Guid? AssigneeId { get; init; }
|
||||
public decimal? EstimatedHours { get; init; }
|
||||
public Guid CreatedBy { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Request model for updating a story
|
||||
/// </summary>
|
||||
public record UpdateStoryRequest
|
||||
{
|
||||
public string Title { get; init; } = string.Empty;
|
||||
public string Description { get; init; } = string.Empty;
|
||||
public string? Status { get; init; }
|
||||
public string? Priority { get; init; }
|
||||
public Guid? AssigneeId { get; init; }
|
||||
public decimal? EstimatedHours { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Request model for assigning a story
|
||||
/// </summary>
|
||||
public record AssignStoryRequest
|
||||
{
|
||||
public Guid AssigneeId { get; init; }
|
||||
}
|
||||
230
colaflow-api/src/ColaFlow.API/Controllers/TasksController.cs
Normal file
230
colaflow-api/src/ColaFlow.API/Controllers/TasksController.cs
Normal file
@@ -0,0 +1,230 @@
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
|
||||
using ColaFlow.Modules.ProjectManagement.Application.Commands.CreateTask;
|
||||
using ColaFlow.Modules.ProjectManagement.Application.Commands.UpdateTask;
|
||||
using ColaFlow.Modules.ProjectManagement.Application.Commands.DeleteTask;
|
||||
using ColaFlow.Modules.ProjectManagement.Application.Commands.AssignTask;
|
||||
using ColaFlow.Modules.ProjectManagement.Application.Commands.UpdateTaskStatus;
|
||||
using ColaFlow.Modules.ProjectManagement.Application.Queries.GetTaskById;
|
||||
using ColaFlow.Modules.ProjectManagement.Application.Queries.GetTasksByStoryId;
|
||||
using ColaFlow.Modules.ProjectManagement.Application.Queries.GetTasksByProjectId;
|
||||
|
||||
namespace ColaFlow.API.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// Tasks API Controller
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/v1")]
|
||||
public class TasksController : ControllerBase
|
||||
{
|
||||
private readonly IMediator _mediator;
|
||||
|
||||
public TasksController(IMediator mediator)
|
||||
{
|
||||
_mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get task by ID
|
||||
/// </summary>
|
||||
[HttpGet("tasks/{id:guid}")]
|
||||
[ProducesResponseType(typeof(TaskDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetTask(Guid id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var query = new GetTaskByIdQuery(id);
|
||||
var result = await _mediator.Send(query, cancellationToken);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get all tasks for a story
|
||||
/// </summary>
|
||||
[HttpGet("stories/{storyId:guid}/tasks")]
|
||||
[ProducesResponseType(typeof(List<TaskDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetStoryTasks(Guid storyId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var query = new GetTasksByStoryIdQuery(storyId);
|
||||
var result = await _mediator.Send(query, cancellationToken);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get all tasks for a project (for Kanban board)
|
||||
/// </summary>
|
||||
[HttpGet("projects/{projectId:guid}/tasks")]
|
||||
[ProducesResponseType(typeof(List<TaskDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetProjectTasks(
|
||||
Guid projectId,
|
||||
[FromQuery] string? status = null,
|
||||
[FromQuery] Guid? assigneeId = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var query = new GetTasksByProjectIdQuery
|
||||
{
|
||||
ProjectId = projectId,
|
||||
Status = status,
|
||||
AssigneeId = assigneeId
|
||||
};
|
||||
var result = await _mediator.Send(query, cancellationToken);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create a new task
|
||||
/// </summary>
|
||||
[HttpPost("stories/{storyId:guid}/tasks")]
|
||||
[ProducesResponseType(typeof(TaskDto), StatusCodes.Status201Created)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> CreateTask(
|
||||
Guid storyId,
|
||||
[FromBody] CreateTaskRequest request,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var command = new CreateTaskCommand
|
||||
{
|
||||
StoryId = storyId,
|
||||
Title = request.Title,
|
||||
Description = request.Description,
|
||||
Priority = request.Priority,
|
||||
EstimatedHours = request.EstimatedHours,
|
||||
AssigneeId = request.AssigneeId,
|
||||
CreatedBy = request.CreatedBy
|
||||
};
|
||||
|
||||
var result = await _mediator.Send(command, cancellationToken);
|
||||
return CreatedAtAction(nameof(GetTask), new { id = result.Id }, result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Update an existing task
|
||||
/// </summary>
|
||||
[HttpPut("tasks/{id:guid}")]
|
||||
[ProducesResponseType(typeof(TaskDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> UpdateTask(
|
||||
Guid id,
|
||||
[FromBody] UpdateTaskRequest request,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var command = new UpdateTaskCommand
|
||||
{
|
||||
TaskId = id,
|
||||
Title = request.Title,
|
||||
Description = request.Description,
|
||||
Status = request.Status,
|
||||
Priority = request.Priority,
|
||||
EstimatedHours = request.EstimatedHours,
|
||||
AssigneeId = request.AssigneeId
|
||||
};
|
||||
|
||||
var result = await _mediator.Send(command, cancellationToken);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Delete a task
|
||||
/// </summary>
|
||||
[HttpDelete("tasks/{id:guid}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> DeleteTask(Guid id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var command = new DeleteTaskCommand { TaskId = id };
|
||||
await _mediator.Send(command, cancellationToken);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Assign a task to a user
|
||||
/// </summary>
|
||||
[HttpPut("tasks/{id:guid}/assign")]
|
||||
[ProducesResponseType(typeof(TaskDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> AssignTask(
|
||||
Guid id,
|
||||
[FromBody] AssignTaskRequest request,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var command = new AssignTaskCommand
|
||||
{
|
||||
TaskId = id,
|
||||
AssigneeId = request.AssigneeId
|
||||
};
|
||||
|
||||
var result = await _mediator.Send(command, cancellationToken);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Update task status (for Kanban board drag & drop)
|
||||
/// </summary>
|
||||
[HttpPut("tasks/{id:guid}/status")]
|
||||
[ProducesResponseType(typeof(TaskDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> UpdateTaskStatus(
|
||||
Guid id,
|
||||
[FromBody] UpdateTaskStatusRequest request,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var command = new UpdateTaskStatusCommand
|
||||
{
|
||||
TaskId = id,
|
||||
NewStatus = request.NewStatus
|
||||
};
|
||||
|
||||
var result = await _mediator.Send(command, cancellationToken);
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Request model for creating a task
|
||||
/// </summary>
|
||||
public record CreateTaskRequest
|
||||
{
|
||||
public string Title { get; init; } = string.Empty;
|
||||
public string Description { get; init; } = string.Empty;
|
||||
public string Priority { get; init; } = "Medium";
|
||||
public decimal? EstimatedHours { get; init; }
|
||||
public Guid? AssigneeId { get; init; }
|
||||
public Guid CreatedBy { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Request model for updating a task
|
||||
/// </summary>
|
||||
public record UpdateTaskRequest
|
||||
{
|
||||
public string Title { get; init; } = string.Empty;
|
||||
public string Description { get; init; } = string.Empty;
|
||||
public string? Status { get; init; }
|
||||
public string? Priority { get; init; }
|
||||
public decimal? EstimatedHours { get; init; }
|
||||
public Guid? AssigneeId { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Request model for assigning a task
|
||||
/// </summary>
|
||||
public record AssignTaskRequest
|
||||
{
|
||||
public Guid? AssigneeId { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Request model for updating task status
|
||||
/// </summary>
|
||||
public record UpdateTaskStatusRequest
|
||||
{
|
||||
public string NewStatus { get; init; } = string.Empty;
|
||||
}
|
||||
@@ -30,8 +30,12 @@ public static class ModuleExtensions
|
||||
services.AddScoped<IProjectRepository, ProjectRepository>();
|
||||
services.AddScoped<IUnitOfWork, UnitOfWork>();
|
||||
|
||||
// Register MediatR handlers from Application assembly
|
||||
services.AddMediatR(typeof(CreateProjectCommand).Assembly);
|
||||
// Register MediatR handlers from Application assembly (v13.x syntax)
|
||||
services.AddMediatR(cfg =>
|
||||
{
|
||||
cfg.LicenseKey = configuration["MediatR:LicenseKey"];
|
||||
cfg.RegisterServicesFromAssembly(typeof(CreateProjectCommand).Assembly);
|
||||
});
|
||||
|
||||
// Register FluentValidation validators
|
||||
services.AddValidatorsFromAssembly(typeof(CreateProjectCommand).Assembly);
|
||||
|
||||
130
colaflow-api/src/ColaFlow.API/Handlers/GlobalExceptionHandler.cs
Normal file
130
colaflow-api/src/ColaFlow.API/Handlers/GlobalExceptionHandler.cs
Normal file
@@ -0,0 +1,130 @@
|
||||
using System.Diagnostics;
|
||||
using FluentValidation;
|
||||
using Microsoft.AspNetCore.Diagnostics;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;
|
||||
|
||||
namespace ColaFlow.API.Handlers;
|
||||
|
||||
/// <summary>
|
||||
/// Global exception handler using IExceptionHandler (.NET 8+)
|
||||
/// Handles all unhandled exceptions and converts them to ProblemDetails responses
|
||||
/// </summary>
|
||||
public sealed class GlobalExceptionHandler : IExceptionHandler
|
||||
{
|
||||
private readonly ILogger<GlobalExceptionHandler> _logger;
|
||||
|
||||
public GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger)
|
||||
{
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
}
|
||||
|
||||
public async ValueTask<bool> TryHandleAsync(
|
||||
HttpContext httpContext,
|
||||
Exception exception,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// Log with appropriate level based on exception type
|
||||
if (exception is ValidationException or DomainException or NotFoundException)
|
||||
{
|
||||
_logger.LogWarning(exception, "Client error occurred: {Message}", exception.Message);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogError(exception, "Internal server error occurred: {Message}", exception.Message);
|
||||
}
|
||||
|
||||
var problemDetails = exception switch
|
||||
{
|
||||
ValidationException validationEx => CreateValidationProblemDetails(httpContext, validationEx),
|
||||
DomainException domainEx => CreateDomainProblemDetails(httpContext, domainEx),
|
||||
NotFoundException notFoundEx => CreateNotFoundProblemDetails(httpContext, notFoundEx),
|
||||
_ => CreateInternalServerErrorProblemDetails(httpContext, exception)
|
||||
};
|
||||
|
||||
httpContext.Response.StatusCode = problemDetails.Status ?? StatusCodes.Status500InternalServerError;
|
||||
await httpContext.Response.WriteAsJsonAsync(problemDetails, cancellationToken);
|
||||
|
||||
return true; // Exception handled
|
||||
}
|
||||
|
||||
private static ProblemDetails CreateValidationProblemDetails(
|
||||
HttpContext context,
|
||||
ValidationException exception)
|
||||
{
|
||||
var errors = exception.Errors
|
||||
.GroupBy(e => e.PropertyName)
|
||||
.ToDictionary(
|
||||
g => g.Key,
|
||||
g => g.Select(e => e.ErrorMessage).ToArray()
|
||||
);
|
||||
|
||||
return new ProblemDetails
|
||||
{
|
||||
Type = "https://tools.ietf.org/html/rfc7231#section-6.5.1",
|
||||
Title = "Validation Error",
|
||||
Status = StatusCodes.Status400BadRequest,
|
||||
Detail = "One or more validation errors occurred.",
|
||||
Instance = context.Request.Path,
|
||||
Extensions =
|
||||
{
|
||||
["traceId"] = Activity.Current?.Id ?? context.TraceIdentifier,
|
||||
["errors"] = errors
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static ProblemDetails CreateDomainProblemDetails(
|
||||
HttpContext context,
|
||||
DomainException exception)
|
||||
{
|
||||
return new ProblemDetails
|
||||
{
|
||||
Type = "https://tools.ietf.org/html/rfc7231#section-6.5.1",
|
||||
Title = "Domain Error",
|
||||
Status = StatusCodes.Status400BadRequest,
|
||||
Detail = exception.Message,
|
||||
Instance = context.Request.Path,
|
||||
Extensions =
|
||||
{
|
||||
["traceId"] = Activity.Current?.Id ?? context.TraceIdentifier
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static ProblemDetails CreateNotFoundProblemDetails(
|
||||
HttpContext context,
|
||||
NotFoundException exception)
|
||||
{
|
||||
return new ProblemDetails
|
||||
{
|
||||
Type = "https://tools.ietf.org/html/rfc7231#section-6.5.4",
|
||||
Title = "Resource Not Found",
|
||||
Status = StatusCodes.Status404NotFound,
|
||||
Detail = exception.Message,
|
||||
Instance = context.Request.Path,
|
||||
Extensions =
|
||||
{
|
||||
["traceId"] = Activity.Current?.Id ?? context.TraceIdentifier
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static ProblemDetails CreateInternalServerErrorProblemDetails(
|
||||
HttpContext context,
|
||||
Exception exception)
|
||||
{
|
||||
return new ProblemDetails
|
||||
{
|
||||
Type = "https://tools.ietf.org/html/rfc7231#section-6.6.1",
|
||||
Title = "Internal Server Error",
|
||||
Status = StatusCodes.Status500InternalServerError,
|
||||
Detail = "An unexpected error occurred. Please contact support if the problem persists.",
|
||||
Instance = context.Request.Path,
|
||||
Extensions =
|
||||
{
|
||||
["traceId"] = Activity.Current?.Id ?? context.TraceIdentifier
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using FluentValidation;
|
||||
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;
|
||||
|
||||
namespace ColaFlow.API.Middleware;
|
||||
|
||||
/// <summary>
|
||||
/// Global exception handler middleware
|
||||
/// </summary>
|
||||
public class GlobalExceptionHandlerMiddleware
|
||||
{
|
||||
private readonly RequestDelegate _next;
|
||||
private readonly ILogger<GlobalExceptionHandlerMiddleware> _logger;
|
||||
|
||||
public GlobalExceptionHandlerMiddleware(
|
||||
RequestDelegate next,
|
||||
ILogger<GlobalExceptionHandlerMiddleware> logger)
|
||||
{
|
||||
_next = next ?? throw new ArgumentNullException(nameof(next));
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
}
|
||||
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _next(context);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await HandleExceptionAsync(context, ex);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleExceptionAsync(HttpContext context, Exception exception)
|
||||
{
|
||||
context.Response.ContentType = "application/json";
|
||||
|
||||
var (statusCode, response) = exception switch
|
||||
{
|
||||
ValidationException validationEx => (
|
||||
StatusCodes.Status400BadRequest,
|
||||
new
|
||||
{
|
||||
StatusCode = StatusCodes.Status400BadRequest,
|
||||
Message = "Validation failed",
|
||||
Errors = validationEx.Errors.Select(e => new
|
||||
{
|
||||
Property = e.PropertyName,
|
||||
Message = e.ErrorMessage
|
||||
})
|
||||
}),
|
||||
DomainException domainEx => (
|
||||
StatusCodes.Status400BadRequest,
|
||||
new
|
||||
{
|
||||
StatusCode = StatusCodes.Status400BadRequest,
|
||||
Message = domainEx.Message
|
||||
}),
|
||||
NotFoundException notFoundEx => (
|
||||
StatusCodes.Status404NotFound,
|
||||
new
|
||||
{
|
||||
StatusCode = StatusCodes.Status404NotFound,
|
||||
Message = notFoundEx.Message
|
||||
}),
|
||||
_ => (
|
||||
StatusCodes.Status500InternalServerError,
|
||||
new
|
||||
{
|
||||
StatusCode = StatusCodes.Status500InternalServerError,
|
||||
Message = "An internal server error occurred"
|
||||
})
|
||||
};
|
||||
|
||||
context.Response.StatusCode = statusCode;
|
||||
|
||||
// Log with appropriate level
|
||||
if (statusCode >= 500)
|
||||
{
|
||||
_logger.LogError(exception, "Internal server error occurred: {Message}", exception.Message);
|
||||
}
|
||||
else if (statusCode >= 400)
|
||||
{
|
||||
_logger.LogWarning(exception, "Client error occurred: {Message}", exception.Message);
|
||||
}
|
||||
|
||||
var jsonResponse = JsonSerializer.Serialize(response, new JsonSerializerOptions
|
||||
{
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
|
||||
});
|
||||
|
||||
await context.Response.WriteAsync(jsonResponse);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
using ColaFlow.API.Extensions;
|
||||
using ColaFlow.API.Middleware;
|
||||
using ColaFlow.API.Handlers;
|
||||
using Scalar.AspNetCore;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
@@ -10,6 +10,10 @@ builder.Services.AddProjectManagementModule(builder.Configuration);
|
||||
// Add controllers
|
||||
builder.Services.AddControllers();
|
||||
|
||||
// Configure exception handling (IExceptionHandler - .NET 8+)
|
||||
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
|
||||
builder.Services.AddProblemDetails();
|
||||
|
||||
// Configure CORS for frontend
|
||||
builder.Services.AddCors(options =>
|
||||
{
|
||||
@@ -34,7 +38,7 @@ if (app.Environment.IsDevelopment())
|
||||
}
|
||||
|
||||
// Global exception handler (should be first in pipeline)
|
||||
app.UseMiddleware<GlobalExceptionHandlerMiddleware>();
|
||||
app.UseExceptionHandler();
|
||||
|
||||
// Enable CORS
|
||||
app.UseCors("AllowFrontend");
|
||||
|
||||
@@ -2,6 +2,12 @@
|
||||
"ConnectionStrings": {
|
||||
"PMDatabase": "Host=localhost;Port=5432;Database=colaflow_pm;Username=colaflow;Password=colaflow_dev_password"
|
||||
},
|
||||
"MediatR": {
|
||||
"LicenseKey": "eyJhbGciOiJSUzI1NiIsImtpZCI6Ikx1Y2t5UGVubnlTb2Z0d2FyZUxpY2Vuc2VLZXkvYmJiMTNhY2I1OTkwNGQ4OWI0Y2IxYzg1ZjA4OGNjZjkiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2x1Y2t5cGVubnlzb2Z0d2FyZS5jb20iLCJhdWQiOiJMdWNreVBlbm55U29mdHdhcmUiLCJleHAiOiIxNzkzNTc3NjAwIiwiaWF0IjoiMTc2MjEyNTU2MiIsImFjY291bnRfaWQiOiIwMTlhNDZkZGZiZjk3YTk4Yjg1ZTVmOTllNWRhZjIwNyIsImN1c3RvbWVyX2lkIjoiY3RtXzAxazkzZHdnOG0weDByanp3Mm5rM2dxeDExIiwic3ViX2lkIjoiLSIsImVkaXRpb24iOiIwIiwidHlwZSI6IjIifQ.V45vUlze27pQG3Vs9dvagyUTSp-a74ymB6I0TIGD_NwFt1mMMPsuVXOKH1qK7A7V5qDQBvYyryzJy8xRE1rRKq2MJKgyfYjvzuGkpBbKbM6JRQPYknb5tjF-Rf3LAeWp73FiqbPZOPt5saCsoKqUHej-4zcKg5GA4y-PpGaGAONKyqwK9G2rvc1BUHfEnHKRMr0pprA5W1Yx-Lry85KOckUsI043HGOdfbubnGdAZs74FKvrV2qVir6K6VsZjWwX8IFnl1CzxjICa5MxyHOAVpXRnRtMt6fpsA1fMstFuRjq_2sbqGfsTv6LyCzLPnXdmU5DnWZHUcjy0xlAT_f0aw"
|
||||
},
|
||||
"AutoMapper": {
|
||||
"LicenseKey": "eyJhbGciOiJSUzI1NiIsImtpZCI6Ikx1Y2t5UGVubnlTb2Z0d2FyZUxpY2Vuc2VLZXkvYmJiMTNhY2I1OTkwNGQ4OWI0Y2IxYzg1ZjA4OGNjZjkiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2x1Y2t5cGVubnlzb2Z0d2FyZS5jb20iLCJhdWQiOiJMdWNreVBlbm55U29mdHdhcmUiLCJleHAiOiIxNzkzNTc3NjAwIiwiaWF0IjoiMTc2MjEyNTU2MiIsImFjY291bnRfaWQiOiIwMTlhNDZkZGZiZjk3YTk4Yjg1ZTVmOTllNWRhZjIwNyIsImN1c3RvbWVyX2lkIjoiY3RtXzAxazkzZHdnOG0weDByanp3Mm5rM2dxeDExIiwic3ViX2lkIjoiLSIsImVkaXRpb24iOiIwIiwidHlwZSI6IjIifQ.V45vUlze27pQG3Vs9dvagyUTSp-a74ymB6I0TIGD_NwFt1mMMPsuVXOKH1qK7A7V5qDQBvYyryzJy8xRE1rRKq2MJKgyfYjvzuGkpBbKbM6JRQPYknb5tjF-Rf3LAeWp73FiqbPZOPt5saCsoKqUHej-4zcKg5GA4y-PpGaGAONKyqwK9G2rvc1BUHfEnHKRMr0pprA5W1Yx-Lry85KOckUsI043HGOdfbubnGdAZs74FKvrV2qVir6K6VsZjWwX8IFnl1CzxjICa5MxyHOAVpXRnRtMt6fpsA1fMstFuRjq_2sbqGfsTv6LyCzLPnXdmU5DnWZHUcjy0xlAT_f0aw"
|
||||
},
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
|
||||
Reference in New Issue
Block a user