E
E
embiid2021-04-08 08:30:06
ASP.NET
embiid, 2021-04-08 08:30:06

How to throw a custom exception?

for example, there is such a custom exception:

public class CustomerExistsException
    {
        public void DisplayException()
        {
            throw new AuthException("The email has already been taken.");
        }
    }

    public class AuthException : Exception
    {
        public AuthException(string message) : base(message) { }
        public AuthException(string message, Exception exception) 
            : base(message, exception) { }
    }


And then how to throw it in the service?
public async Task<CustomerDto> Register(CustomerDto customerModel, string password)
        {
            if (await EmailExists(customerModel.Email))
            {
                //Cannot implicitly convert type CustomerExistsException to System.Exception
                //throw new CustomerExistsException();
            }
        }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
cicatrix, 2021-04-08
@embiid

Throwing an exception is the most "expensive" of all possible solutions to a problem in terms of performance. In addition, this is not an exception at all, but a completely regular situation. A simple check in the form of a call to bool CustomerExists would look much more appropriate here. In addition, you already have this check.
And so, yes, the class of any exception must be a successor of System.Exception

E
edward_freedom, 2021-04-08
@edward_freedom

regular function
new CustomerExistsException().DisplayException();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question