无法在使用转换器时从 “convertToDatabaseColumn” 中抛出异常。

huangapple go评论75阅读模式
英文:

Unable to throw exception from "convertToDatabaseColumn" while using converter

问题

我正在制作一个用于类的转换器,其中包括解析JSON。如果JSON解析失败,我想要抛出异常,但只允许我使用try/catch捕获异常。我需要将异常抛给上层以传播错误。我尝试在函数上添加throws,但它说不允许。有没有办法将异常传播到上层?

@Converter(autoApply = true)
public static class classConverter implements AttributeConverter<Class, String> {

    @Override
    public String convertToDatabaseColumn(Class classobj) {

        ObjectMapper object = new ObjectMapper();
        String json = new String();

        try {
            json = object.writeValueAsString(classobj);
        } catch (JsonProcessingException e) {
            // 当我尝试抛出异常时会出错
            throw e;
        }

        return json;

    }
}
英文:

I am making a converter for a class and it includes parsing a JSON. I want to throw the exception if the json parsing fails but it is only allowing me to try/catch the exception. I need to throw the exception to the upper layers in order to propagate the error. I tried adding throws at the function but it says that it is not allowed. Is there any way to propagate the exception to the upper layers?

    @Converter( autoApply = true)
    public static class classConverter implements AttributeConverter&lt;Class, String&gt; {
        
        @Override
        public String convertToDatabaseColumn(Class classobj) {
                        
            ObjectMapper object = new ObjectMapper();
            String json = new String();

                try {
                    json = object.writeValueAsString(classobj);
                } catch (JsonProcessingException e) {
                    // Gives error when i try to throw the error
                    throw e;

                }

            
            return json;
            
        }

答案1

得分: 3

你可以将它包装成RuntimeException的子类。

声明一个新的RuntimeException

public class JsonProcessingRuntimeException extends RuntimeException {
}

然后在你的类中抛出它:

} catch (JsonProcessingException e) {
    // 当我尝试抛出错误时会出现错误
    throw new JsonProcessingRuntimeException(e);
}

在上层你可以捕获JsonProcessingRuntimeException

英文:

You can wrap it into a sub class of RuntimeExcpetion.

Declare a new RuntimeException:

public class JsonProcessingRuntimeException extends RuntimeExcpetion{
}

and throw it in your class:

} catch (JsonProcessingException e) {
    // Gives error when i try to throw the error
    throw new JsonProcessingRuntimeException (e);

}

And in upper layer you can catch the JsonProcessingRuntimeException.

huangapple
  • 本文由 发表于 2020年7月22日 02:46:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/63021146.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定