简体   繁体   中英

How to check or throw user defined exception for value which is not there in ENUM , Let say I passes Metadata= "DF" from postman

public enum Metadata{
    AC, CD;
}

I am getting json parser error when passing value which is not there in enum..and that error is very lengthy and not readable to user ..instead I should get a proper readable message but I dont know how to resolve this error

instead I should get a proper readable message

Then you need to implement a method that would validate the input and in the case if provided enum-name doesn't exist it would throw an exception with a suitable message.

That's how it might look like:

public enum Metadata{
    AC, CD;
    
    public static Metadata get(String name) {
        if (!isValid(name)) throw new MyExceptoin("message");

        return valueOf(name);
    }
    
    public static boolean isValid(String name) {
        
        return Arrays.stream(values()).anyMatch(e -> e.name().equals(name));
    }
}

It would be more cleaner approach than catching an IllegalArgumentException (because it's a runtime exception) that can be thrown valueOf() , and then throwing a desired exception from the catch block. And you can't gain a significant performance advantage with this approach since there will be only a few enum-members.

Just for illustrative purposes, that's how an exception can be caught and rethrowing:

public static Metadata get(String name) {
    try {
        return valueOf(name);
    } catch (IllegalAccessException e) {
        throw new MyExceptoin("message");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM