質問

I'm trying to serialize a custom Exception in Java using writeValueAsString() method from Jackson library. I intend to send it by HTTP to another machine. This is working partialy because not all fields are included in JSON after serialize. The top level exception Throwable implements Serializable interface, and also has some constructors that add info about what is to be serialized. I suppose the truth is somewhere here. Please help with some advices. Here is my custom exception code:

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

somewhere in code I use:

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

and in other place I have:

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

The result JSON object is:

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

Here I also expect to see my type and severity fields.

役に立ちましたか?

解決

I made type and severity non-static, and it seems to be working fine. I used the following code, and I see both type and severity in the serialized output.

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

... and

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

Hope this helps!

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top