Ahed Saed
Ahed Saed

Reputation: 21

How to manipulate error code enum

I have the below code:

public enum CpAutoExecCode implements CpAutoErrorCode {
    //TODO - List of the execution error codes
    //Error code sample
    GENERIC_EXECUTION_ERROR(200,"Generic execution error code description"),
    MISSING_REQUIRED_FIELD(201,"Required field %s is missing from model : %s");

    private final int number;
    private final String description;

    private CpAutoExecCode(int number,String description) {
        this.number = number;
        this.description = description;
    }

    @Override
    public int getNumber() {
        return number;
    }

    @Override
    public String getDescription() {
        return description;
    } 
}

i want to assign the required field and the object name in the %s . does anyone have a simple way to do it?

Upvotes: 1

Views: 129

Answers (2)

Mick Mnemonic
Mick Mnemonic

Reputation: 7956

You can use String.format() with CpAutoExecCode.getDescription():

String formattedMessage = String.format(MISSING_REQUIRED_FIELD.getDescription(), 
                                 myMissingField, 
                                 myModel);

Upvotes: 1

epoch
epoch

Reputation: 16615

It really depends on your usage of the class.

For instance, if you have a custom exception that takes in the enum, you can do something like this:

class MyException {

    int code;

    MyException(CpAutoErrorCode error, Object[] args) {
        super(format(error.getDescription(), args));
    }

    private static String format(String error, Object[] args) {
        // interpolate your string with the values
    }
}

Or you can build the same type of structure on the enum class itself.

Upvotes: 0

Related Questions