added exception handling
This commit is contained in:
1 parent
ffb308dc52
commit
5b64b32721
2 files changed
+18
-11
No files matched your search
@@ -1,19 +1,15 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using api.Services;
|
||||
using api.DTOs;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace api.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public class PersonController : ControllerBase
|
||||
public class PersonController(IPersonService personService) : ControllerBase
|
||||
{
|
||||
private readonly IPersonService _personService;
|
||||
|
||||
public PersonController(IPersonService personService)
|
||||
{
|
||||
_personService = personService;
|
||||
}
|
||||
private readonly IPersonService _personService = personService;
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> GetAll()
|
||||
@@ -39,8 +35,20 @@ namespace api.Controllers
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> Add(PersonDto personDto)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _personService.AddPersonAsync(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}")]
|
||||
|
||||
@@ -24,10 +24,9 @@ public sealed class Person
|
||||
realName = realName.Trim();
|
||||
|
||||
// TODO: Error Handling
|
||||
if (username.Length is < 3 or > 32) throw new Exception();
|
||||
if (realName.Length == 0) throw new Exception();
|
||||
if (birthday >= DateOnly.FromDateTime(DateTime.Today)) throw new Exception();
|
||||
if (!IsAtLeast16(birthday)) 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 ArgumentException("Name cannot be empty");
|
||||
if (!IsAtLeast16(birthday) || birthday >= DateOnly.FromDateTime(DateTime.Today)) throw new ArgumentException("Person must be at least 16 years old.");
|
||||
|
||||
return new Person(username, realName, birthday);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user