5

我正在尝试使用 Jackson 库中的 writeValueAsString() 方法在 Java 中序列化自定义异常。我打算通过 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);
}
}

我使用的代码中的某处:

MyException exc = new MyException("Here goes my exception.");
MyException.setType(exc.getClass().getSimpleName());    
MyException.setSeverity("Major");
throw exc;

在其他地方我有:

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

结果 JSON 对象为:

{"cause":null,"message":"Here goes my exception.","localizedMessage":"Here goes my exception.","stackTrace":[{...a usual stack trace...}]}

在这里,我还希望看到我的类型和严重性字段。

4

1 回答 1

5

我做了typeseverity静态的,它似乎工作正常。我使用了以下代码,并且在序列化输出中看到了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);
    }
}

... 和

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

希望这可以帮助!

于 2013-09-27T15:39:32.723 回答