Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize fields in custom exception in Java

Let's say I have my custom RuntimeException, where MyEntity is JPA @Entity:

@Getter
public class MyEntityAlreadyExistingException extends RuntimeException {

    private final MyEntity myEntity;

    public MyEntityAlreadyExistingException(MyEntity myEntity) {
        super(MessageFormat.format("MyEntity with name \"{0}\" already exists", myEntity.getName()));
        this.myEntity = myEntity;
    }
}

Sonar hints me to make myEntity transient or serializable.

How should I deal with this situation?

I don't use any RMI, remoting whatsoever. It is relatively simple Spring Boot web application with JPA in place.

What advantages are there I could leverage later on if I made myEntity serializable?

like image 890
Patrik Mihalčin Avatar asked Jan 24 '18 10:01

Patrik Mihalčin


1 Answers

How should I deal with this situation?

So, if you don't use any RMI and your application runs in a protected environment (and you want to make Sonar happy) - mark all fields in your custom exception class as transient, or leave it as is.

If we are talking about the distributed environment, then serialization should be made with great care - your class must have a predictable behavior once it has been serialized. In this situation, make instance fields that are part of the logical state of the object Serializable, otherwise - mark them as transient.

P.S. Why Sonar warns you.

like image 167
Oleksandr Pyrohov Avatar answered Oct 19 '22 22:10

Oleksandr Pyrohov