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:
- 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>
- 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
}
- The use of the @StandardException annotation will automatically generate the following methods and fields:
- default constructor
- Constructor with message parameter
- Constructor with the cause parameter
- Constructor with the parameters message and cause.
- An error code field.
- Overriding the getMessage() method
- Overriding the toString() method
- overriding the equals() method
- Overriding the hashCode() method
Using the @StandardException annotation can streamline the creation of custom exception classes, improving the readability and conciseness of the code.