How to use the @StandardException annotation in Lombok?

The @StandardException annotation in Lombok is used to generate standard exception classes. Here are the steps for using the @StandardException annotation:

  1. First, add the Lombok dependency in the project’s pom.xml file.
<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>1.18.20</version>
  <scope>provided</scope>
</dependency>
  1. Add the annotation @StandardException to the class that needs to generate standard exception classes.
import lombok.*;

@StandardException
public class CustomException extends RuntimeException {
    private String errorCode;

    public CustomException(String errorCode, String message) {
        super(message);
        this.errorCode = errorCode;
    }
    
    // getters and setters
}
  1. The use of the @StandardException annotation will automatically generate the following methods and fields:
  1. default constructor
  2. Constructor with message parameter
  3. Constructor with the cause parameter
  4. Constructor with the parameters message and cause.
  5. An error code field.
  6. Overriding the getMessage() method
  7. Overriding the toString() method
  8. overriding the equals() method
  9. Overriding the hashCode() method

Using the @StandardException annotation can streamline the creation of custom exception classes, improving the readability and conciseness of the code.

bannerAds