As we saw earlier, when an error occurs in our system, we encounter what is defined as an exception.
In this post, we will see an extension of that post. Here, we will create our own exceptions.
The main benefit of having custom exceptions is that they allow us to control our code, and, more importantly, they are mainly used for monitoring our website.
For our example, let's imagine we have an invoice system, and a user tries to access an invoice that does not belong to them.
1 - Create a Custom Exception
To create a custom exception, we only need to create a class that implements the Exception object and define a constructor, as shown in the example.
public class FacturaDiferenteClienteException : Exception
{
public FacturaDiferenteClienteException(string message) : base(message)
{
Console.WriteLine(message);
Util.EnviarEmailAlerta("Intento de hackeo", message);
}
}
To simulate a system, I created a Util
class that contains a EnviarEmailAlerta
method, since in this particular example it's either a serious bug or a hacking attempt.
2 - Use a Custom Exception
To use the exception we just created, we need to instantiate it manually. For this, and to speed up the example, I created a class called Repository to which we pass two IDs, and it simply returns true or false. (the complete code is on GitHub, link below)
Let's get to it: we make the call, and if it returns false, it means the client and the owner of the invoice do not match. In that case, we throw our exception
, as shown in the following code:
if(!repo.ClienteYFacturaDuenoSonElMismo(clienteId, facturaId))
{
throw new FacturaDiferenteClienteException($"El cliente {clienteId} esta intentando acceder a la factura {facturaId} que no le corresponde.");
}
If there is any problem you can add a comment bellow or contact me in the website's contact form