added exception handling

This commit is contained in:
marco committed 2026-08-31 13:43:43 +02:00
1 parent ffb308dc52
commit 5b64b32721
2 files changed
+18 -11

No files matched your search

+15 -7
View File
@@ -1,19 +1,15 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using api.Services; using api.Services;
using api.DTOs; using api.DTOs;
using Microsoft.EntityFrameworkCore;
namespace api.Controllers namespace api.Controllers
{ {
[ApiController] [ApiController]
[Route("api/[controller]")] [Route("api/[controller]")]
public class PersonController : ControllerBase public class PersonController(IPersonService personService) : ControllerBase
{ {
private readonly IPersonService _personService; private readonly IPersonService _personService = personService;
public PersonController(IPersonService personService)
{
_personService = personService;
}
[HttpGet] [HttpGet]
public async Task<IActionResult> GetAll() public async Task<IActionResult> GetAll()
@@ -38,9 +34,21 @@ namespace api.Controllers
[HttpPost] [HttpPost]
public async Task<IActionResult> Add(PersonDto personDto) public async Task<IActionResult> Add(PersonDto personDto)
{
try
{ {
await _personService.AddPersonAsync(personDto); await _personService.AddPersonAsync(personDto);
return CreatedAtAction(nameof(GetByUsername), new { username = personDto.Username }, personDto); return CreatedAtAction(nameof(GetByUsername), new { username = personDto.Username }, personDto);
}
catch (ArgumentException ex)
{
return BadRequest(ex.Message);
}
catch (DbUpdateException)
{
return Conflict("Username already exists");
}
} }
[HttpPut("username/{username}")] [HttpPut("username/{username}")]
+3 -4
View File
@@ -24,10 +24,9 @@ public sealed class Person
realName = realName.Trim(); realName = realName.Trim();
// TODO: Error Handling // TODO: Error Handling
if (username.Length is < 3 or > 32) throw new Exception(); if (username.Length is < 3 or > 32) throw new ArgumentException("Username must be 3-32 chars.");
if (realName.Length == 0) throw new Exception(); if (realName.Length == 0) throw new ArgumentException("Name cannot be empty");
if (birthday >= DateOnly.FromDateTime(DateTime.Today)) throw new Exception(); if (!IsAtLeast16(birthday) || birthday >= DateOnly.FromDateTime(DateTime.Today)) throw new ArgumentException("Person must be at least 16 years old.");
if (!IsAtLeast16(birthday)) throw new Exception();
return new Person(username, realName, birthday); return new Person(username, realName, birthday);
} }