Skip to content

Commit

Permalink
Tested and fixed ModbusSerializationCatcher
Browse files Browse the repository at this point in the history
  • Loading branch information
retrodaredevil committed Jun 4, 2022
1 parent 6d733c7 commit 417dfc7
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,21 @@ public ModbusSerializationCatcher(BeanPropertyWriter base) {
@Override
public void serializeAsField(Object bean, JsonGenerator gen, SerializerProvider prov) throws Exception {
try {
System.out.println("Serializing: " + _name);
super.serializeAsField(bean, gen, prov);
} catch (ErrorCodeException ex) {
} catch (Exception ex) { // likely an InvocationTargetException, but catch exception in case it is anything else
final ErrorCodeException actual;
if (ex instanceof ErrorCodeException) {
actual = (ErrorCodeException) ex;
} else {
if (ex.getCause() instanceof ErrorCodeException) {
actual = (ErrorCodeException) ex.getCause();
} else {
throw ex;
}
}
gen.writeFieldName(_name);
gen.writeString("Modbus Exception: " + ex.getExceptionCode());
gen.writeString("Modbus Exception: " + actual.getExceptionCode());
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package me.retrodaredevil.solarthing.program.check;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import me.retrodaredevil.io.modbus.ModbusMessages;
import me.retrodaredevil.io.modbus.handling.ErrorCodeException;
import me.retrodaredevil.solarthing.util.JacksonUtil;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

class ModbusSerializationCatcherTest {

@Test
void test() throws JsonProcessingException {
ObjectMapper modbusCatchingMapper = JacksonUtil.defaultMapper();
modbusCatchingMapper.registerModule(ModbusSerializationCatcher.createModule(TestObject.class));
assertEquals("{\"test1\":5,\"test2\":5,\"test3\":\"Modbus Exception: 2\"}", modbusCatchingMapper.writeValueAsString(new TestObject()));
}

private static class TestObject {
@JsonProperty
private int test1 = 5;
@JsonProperty
private int test2 = 5;

@JsonProperty
private int getTest3() {
throw new ErrorCodeException(ModbusMessages.createMessage(131, new int[0]), 3, 2);
}
}
}

0 comments on commit 417dfc7

Please sign in to comment.