如何检查或投掷用户定义的异常,以了解枚举中不存在的值,请说我通过元数据=“ DF”来自邮递员

发布于 2025-02-08 21:08:18 字数 110 浏览 1 评论 0原文

public enum Metadata{
    AC, CD;
}

我在传递枚举中不存在的值时会遇到JSON解析器错误。该错误非常漫长且对用户不可读取。

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

苏辞 2025-02-15 21:08:18

相反,我应该得到一个适当的可读消息

,然后您需要实现一种可以验证输入的方法,如果提供了 enum-name ,则不存在,它将带有适当的消息的例外。

这样就是这样:

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));
    }
}

比捕获IllegalArgumentException(因为它是一个运行时异常),它可以更干净,可以抛出value> value> valueof(),然后扔一个catch块所需的例外。而且,这种方法将无法获得显着的性能优势,因为只有少数枚举会员。

仅出于说明目的,这就是可以捕获和复发的方式:

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

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");
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文