7

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?

Patrik Mihalčin
  • 3,341
  • 7
  • 33
  • 68
  • You don't have any disadvantages in implementing serialize interface but the only problem is with transient as the entity class be will serialized when the response is returned from the request method. – Prasad Jan 24 '18 at 10:45
  • https://stackoverflow.com/questions/7683739/why-my-exception-class-needs-to-be-serialized#answer-7683839 – Oleksandr Pyrohov Jan 24 '18 at 17:10

1 Answers1

3

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.

Oleksandr Pyrohov
  • 14,685
  • 6
  • 61
  • 90