-2

So lets say we have a AccountController

And has a method like this for registering:

    [HttpPost("register")]
    public ActionResult Register(RegisterDto user)
    {
        try
        {
            accountService.Register(user);
            return Ok();
        }
        catch(Exception ex)
        {
            return BadRequest(ex.Message);
        }
    }

For registering, your EmailAddress must not be used and Password must meed a criteria

The validation exists inside accountService and does something like this:

    public void Register(RegisterDto user)
    {
        accountValidator.ValidateRegistration(user);
        accountHandler.Register(user);
    }

Notice the Register method is void, so it does not return anything, and the method ValidateRegistration looks like this

    public void ValidateRegistration(RegisterDto user)
    {
        if (accountRepository.UserExists(user.Email))
        {
            throw new ExistingAccountAssociatedWithThisEmailAddressException();
        }
        if(!Regex.IsMatch(user.Password, passwordRegex))
        {
            throw new PasswordDoesNotMeetCriteriaException();
        }
    }

I am throwing exception with specific name so I can pass this back to the view, but I am wondering what is the best way to do something like this ? Creating specific Exceptions and throwing them ? I dont want to pass a string back

Nesquikk M
  • 121
  • 3
  • 12
  • 3
    Do not use void with async, return Task. – Carlos Garcia Jan 10 '21 at 14:11
  • this is off-topic for stackoverflow. personally, I'd prefer returning status of operations and other relevant details instead of throwing exceptions. your catch block does not filter on your exception types. so if any other exception occurs, you won't be able to trace it in logs – Yehor Androsov Jan 10 '21 at 14:14
  • It was a mistake to keep it in there sorry, I removed all Task/async, as I am interessted in the best approach with validation and returning message/validation errors – Nesquikk M Jan 10 '21 at 14:14
  • 1
    FluentValidation lib https://docs.fluentvalidation.net/en/latest/index.html may be a good orientation for common concepts. – Christoph Lütjen Jan 10 '21 at 15:19

1 Answers1

0

Using specific exceptions is a good practice, in my opinion, as they explain better a developer's intentions.

I can recommend two ways that may help refine your code:

  • Let all input-related exceptions inherit from a base exception named for example "BadInputException" (or "DomainException", from the perspective of clean architecture). This way you can catch the base exception then return BadRequest back to client.
  • Use asp.net core's middleware to handle such exception (here's an example), instead of try/catch block in every action. This way you would make your code cleaner.
desertech
  • 911
  • 3
  • 7