lex*_*exx 3 java serialization json custom-exceptions jackson
我正在尝试使用Jackson库中的writeValueAsString()方法序列化Java中的自定义Exception。我打算通过HTTP将其发送到另一台计算机。这是局部工作的,因为序列化后并非所有字段都包含在JSON中。顶级异常Throwable实现了Serializable接口,并且还具有一些构造函数,这些构造函数添加有关要序列化的内容的信息。我想真相就在这里。请提供一些建议。这是我的自定义异常代码:
import java.io.Serializable;
public class MyException extends RuntimeException{
private static String type = null;
private static String severity = null;
// somewhere on google I red that should use setters to make serialize work
public static void setType(String type) {
MyException.type = type;
}
public static void setSeverity(String severity) {
MyException.severity = severity;
}
public MyException(String message) {
super(message);
}
}
Run Code Online (Sandbox Code Playgroud)
我在代码中使用的某处:
MyException exc = new MyException("Here goes my exception.");
MyException.setType(exc.getClass().getSimpleName());
MyException.setSeverity("Major");
throw exc;
Run Code Online (Sandbox Code Playgroud)
在其他地方,我有:
ObjectMapper mapper = new ObjectMapper();
try {
responseBuilder.entity(mapper.writeValueAsString(MyException) );
}
catch (JsonGenerationException e) {e.printStackTrace(); }
catch (JsonMappingException e) {e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
Run Code Online (Sandbox Code Playgroud)
结果JSON对象为:
{"cause":null,"message":"Here goes my exception.","localizedMessage":"Here goes my exception.","stackTrace":[{...a usual stack trace...}]}
Run Code Online (Sandbox Code Playgroud)
在这里,我还希望看到我的类型和严重性字段。
我提出type
和severity
非静态的,它似乎是工作的罚款。我使用了以下代码,type
并且severity
在序列化的输出中看到了两者。
public class MyException extends RuntimeException
{
private String type = null;
private String severity = null;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSeverity() {
return severity;
}
public void setSeverity(String severity) {
this.severity = severity;
}
public MyException(String message) {
super(message);
}
}
Run Code Online (Sandbox Code Playgroud)
...和
MyException exc = new MyException("Here goes my exception.");
exc.setType(exc.getClass().getSimpleName());
exc.setSeverity("Major");
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(exc));
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
归档时间: |
|
查看次数: |
6989 次 |
最近记录: |