英文:
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<Class, String> {
@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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论