I am still very much an amateur programmer trying to tune my skills and one habit which I read about is adding a consistent API response to ensure users are getting consistent results from my API. So I have created the following model:
public class ResponseDTO<T>
{
public required bool Succeeded { get; set; }
public required string Message { get; set; } = "";
public required int StatusCode {get; set;}
public string[]? Errors { get; set; }
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public Pagination? Pagination {get; set;}
public T Data { get; set; }
}
It was unclear if from best practices if the data is suppose to be a single result for T and not a List should I ignore the Pagination? by using the JsonIgnore attribute or should I always return pagination data.
My second issue is how to capture errors during some requests. For instance, for a document upload request I have the following controller:
public async Task<IActionResult> AddRevisedCertificationAsync([FromForm] AddDocumentDTO addDocumentDTO)
{
try
{
var documentDTO = await _documentsService.AddRevisedCertificationAsync(addDocumentDTO);
return Ok(new ResponseDTO<DocumentDTO>(){
Succeeded = true,
StatusCode = 200,
Message = "The file have been successfully uploaded.",
Data = documentDTO,
Pagination = null});
}
catch(Exception ex)
{
var documentDTO = await _documentsService.AddRevisedCertificationAsync(addDocumentDTO);
return Ok(new ResponseDTO<DocumentDTO>(){
Succeeded = false,
StatusCode = 400,
Message = "The files were not uploaded due to a system error.",
Data = null,
Pagination = null});
}
}
Should I be doing a try and catch statement in every controller to catch errors and return the result back as a status code despite the overall status code from the request would show 200 since I am returning with Ok()? Just feels weird. Also, say I know there are two possible exceptions. One the document didnt upload to our cloud storage which is box from some unknown error or the file should have been a pdf. Should I create if statements in my catch statement looking for thrown exception types? Like throw a 400 exception in my service layer back to my controller so the if statement in catch will indicate failed to upload since it need pdf and throw a 500 exception in the service layer if the document did not upload to box from a system error and again catch it in the if statement?
I am just struggling with how this should all work so I can implement it consistently through my application.