Authentication and Authorization - Login

Solution - Exception Handling


I finished! On to the next chapter


Solution: Exception Handling

In the Conduit.Models Project

Add a new class in the Exceptions Namespace
  • Name it LoginFailedException
  • Inherits from Exception
  • Add a constructor with a message parameter type string
  • Pass the parameter to the base class

In the Conduit.Api Project

Modify UsersController.LoginAsync Method
  • Add a try...catch block around the existing code
    • Catch an Exception
    • Log the error
    • Return a 500
  • Add a second catch block
    • Catch the LoginFailedException
    • Log the warning
    • Return a 400 or a 422

Here's the code for the LoginFailedException.cs File:

using System;

namespace Conduit.Models.Exceptions
    public class LoginFailedException : Exception
        public LoginFailedException(string message) : base(message)


Here is the code for the LoginAsync Method in the UsersController.cs File:

        public async Task<IActionResult> LoginAsync([FromBody] UserRequest<Login> req)
                User user = await AccountRepo.LoginAsync(req.User).ConfigureAwait(false);
                return Ok(new { user });
            catch (LoginFailedException ex)
                Logger.LogWarning(ex.Message, ex);
                return StatusCode(422, ex.ToDictionary());
            catch (Exception e)
                Logger.LogError(e.Message, e);
                return StatusCode(500, e.Message);