user3442470
user3442470

Reputation: 439

Making a custom Exception with parameters

I'm trying to make a custom exception, the only thing that this custom Exception has to do is to change the message of the exception but have all the attributes of the original exception.

The idea is that the message will change based on the parameter I send.

public class ServiceDireccionException : Exception
{

    public ServiceDireccionException(string type) : base(GetMessage(type)) { }

    public enum TypeOfService
    {
        Provincia,
        Municipio,
        Localidad
    }

    private static string GetMessage(string type)
    {
        string message = "";

        switch (type)
        {
            case nameof(TypeOfService.Provincia):
                message = ("Sucedio un error al buscar la/s" + TypeOfService.Provincia.ToString() + "/s");
                break;

            case nameof(TypeOfService.Municipio):
                message = ("Sucedio un error al buscar lo/s" + TypeOfService.Municipio.ToString() + "/s");
                break;

            case nameof(TypeOfService.Localidad):
                message = ("Sucedio un error al buscar la/s" + TypeOfService.Localidad.ToString() + "/es");
                break;
        }

        return message;
    }

}

When I want to use it in a try catch I can't pass the argument:

    catch (ServiceDireccionException ex) //<-- It does not prompt me to pass a string.
    {
        throw ex;
    }

Upvotes: 2

Views: 6063

Answers (1)

Tom Schardt
Tom Schardt

Reputation: 498

you would use it like

throw new ServiceDireccionException(TypeOfService.Provincia);

but therefore you need to change the constructor parameter type to

public ServiceDireccionException(TypeOfService type) : base(GetMessage(type)) { }

To keep information it should contain inner exception

catch (ServiceDireccionException ex) 
{
    throw new ServiceDireccionException(ex, TypeOfService.Provincia);
}

therefore the constructor will be something like

public ServiceDireccionException(Exception innerException, TypeOfService type) 
    : base(GetMessage(type), innerException) 
{
}

to get the message use

private static string GetMessage(TypeOfService type)
{
    switch (type)
    {
        case TypeOfService.Provincia:
            return $"Sucedio un error al buscar la/s {type}/s";

        case TypeOfService.Municipio:
            return $"Sucedio un error al buscar lo/s {type}/s";

        case TypeOfService.Localidad:
            return $"Sucedio un error al buscar la/s {type}/es";
    }

    return $"Unknown TypeOfService: {type}";
}

Upvotes: 5

Related Questions