using ErrorOr;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace MuiCharts.Api.Controllers;
///
/// Base class for API controllers that provides common functionality and error handling.
///
/// The type of the derived controller.
[ApiController]
[Route("[controller]")]
public abstract class ApiControllerBase(ILogger logger)
: ControllerBase where T : ApiControllerBase
{
///
/// Gets the logger instance used for logging.
///
protected ILogger Logger { get; } = logger;
///
/// Handles the response for a list of errors.
///
/// The list of errors.
/// An representing the response.
protected IActionResult Problem(List errors)
{
if (errors.All(error => error.Type == ErrorType.Validation))
{
ModelStateDictionary modelState = new();
foreach (Error error in errors)
modelState.AddModelError(error.Code, error.Description);
return ValidationProblem(modelState);
}
Error firstError = errors[0];
Logger.LogError("An error occured during request processing: {Error}", firstError);
int statusCode = firstError.Type switch
{
ErrorType.Validation => StatusCodes.Status400BadRequest,
ErrorType.Unauthorized => StatusCodes.Status401Unauthorized,
ErrorType.Forbidden => StatusCodes.Status403Forbidden,
ErrorType.NotFound => StatusCodes.Status404NotFound,
ErrorType.Conflict => StatusCodes.Status409Conflict,
_ => StatusCodes.Status500InternalServerError
};
return Problem(
statusCode: statusCode,
detail: firstError.Description
);
}
}