diff --git a/DigitalData.Core.API/ReadControllerBaseWithErrorHandling.cs b/DigitalData.Core.API/ReadControllerBaseWithErrorHandling.cs new file mode 100644 index 0000000..cf88ce1 --- /dev/null +++ b/DigitalData.Core.API/ReadControllerBaseWithErrorHandling.cs @@ -0,0 +1,86 @@ +using DigitalData.Core.Abstractions.Application; +using DigitalData.Core.DTO; +using Microsoft.AspNetCore.Mvc; + +namespace DigitalData.Core.API +{ + /// + /// A base controller class providing Read operation for a specified entity type, + /// with enhanced error handling to ensure robust and reliable API endpoints. + /// + /// The Data Transfer Object type for read operations. + /// The entity type CRUD operations will be performed on. + /// The type of the entity's identifier. + [ApiController] + [Route("api/[controller]")] + public class ReadControllerBaseWithErrorHandling : ControllerBase + where TBasicCRUDService : IBasicCRUDService + where TReadDto : class + where TEntity : class + { + protected readonly ILogger _logger; + protected readonly TBasicCRUDService _service; + + /// + /// Initializes a new instance of the CRUDControllerBase class with specified logger and CRUD service. + /// + /// The logger to be used by the controller. + /// The CRUD service handling business logic for the entity. + public ReadControllerBaseWithErrorHandling( + ILogger logger, + TBasicCRUDService service) + { + _logger = logger; + _service = service; + } + + /// + /// Retrieves an entity by its identifier. + /// + /// The identifier of the entity to retrieve. + /// A task that represents the asynchronous read operation. The task result contains the action result. + [HttpGet("{id}")] + public virtual async Task GetById([FromRoute] TId id) + { + try + { + return await _service.ReadByIdAsync(id).ThenAsync( + Success: Ok, + Fail: IActionResult (messages, notices) => + { + _logger.LogNotice(notices); + return NotFound(messages); + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "{Message}", ex.Message); + return StatusCode(StatusCodes.Status500InternalServerError); + } + } + + /// + /// Retrieves all entities. + /// + /// A task that represents the asynchronous read-all operation. The task result contains the action result. + [HttpGet] + public virtual async Task GetAll() + { + try + { + return await _service.ReadAllAsync().ThenAsync( + Success: Ok, + Fail: IActionResult (messages, notices) => + { + _logger.LogNotice(notices); + return NotFound(messages); + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "{Message}", ex.Message); + return StatusCode(StatusCodes.Status500InternalServerError); + } + } + } +} \ No newline at end of file