Refactor error handling in controllers

Removed try-catch blocks from various controller methods to simplify error handling and allow exceptions to propagate naturally. Streamlined error logging and response handling using the `ThenAsync` method, enhancing code readability and reducing redundancy. Adjusted conditional checks for improved clarity.
This commit is contained in:
Developer 02
2025-05-09 10:42:11 +02:00
parent 972b258706
commit 5ce6c25393
6 changed files with 183 additions and 276 deletions

View File

@@ -63,23 +63,15 @@ public class EmailTemplateController : ControllerBase
[HttpGet]
public async Task<IActionResult> Get([FromQuery] ReadEmailTemplateQuery? emailTemplate = null)
{
try
if (emailTemplate is null || (emailTemplate.Id is null && emailTemplate.Type is null))
{
if (emailTemplate is null || (emailTemplate.Id is null && emailTemplate.Type is null))
{
var temps = await _repository.ReadAllAsync();
return Ok(_mapper.Map<IEnumerable<EmailTemplateDto>>(temps));
}
else
{
var temp = await _mediator.Send(emailTemplate);
return temp is null ? NotFound() : Ok(temp);
}
var temps = await _repository.ReadAllAsync();
return Ok(_mapper.Map<IEnumerable<EmailTemplateDto>>(temps));
}
catch (Exception ex)
else
{
_logger.LogError(ex, "{Message}", ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError);
var temp = await _mediator.Send(emailTemplate);
return temp is null ? NotFound() : Ok(temp);
}
}
@@ -107,33 +99,20 @@ public class EmailTemplateController : ControllerBase
[HttpPut]
public async Task<IActionResult> Update([FromQuery] EmailTemplateQuery? temp = null, [FromBody] UpdateEmailTemplateCommand? update = null)
{
try
if (update is null)
{
if (update is null)
{
await _mediator.Send(new ResetEmailTemplateCommand(temp));
return Ok();
}
else if(temp is null)
{
return BadRequest("No both id and type");
}
else
{
update.EmailTemplateQuery = temp;
await _mediator.Send(update);
return Ok();
}
await _mediator.Send(new ResetEmailTemplateCommand(temp));
return Ok();
}
catch(NotFoundException)
else if (temp is null)
{
return BadRequest();
return BadRequest("No both id and type");
}
catch (Exception ex)
else
{
_logger.LogError(ex, "An unexpected error occurred. {message}", ex.Message);
return new StatusCodeResult(StatusCodes.Status500InternalServerError);
update.EmailTemplateQuery = temp;
await _mediator.Send(update);
return Ok();
}
}
}