This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to the original Chinese version. I am continuously working to improve the translation.
This series documents my journey of learning Spring and React from scratch while building a small project. It's meant for reference only and is not intended as a formal tutorial. For an overview of the project, check out Ep.0.
Here are some loose ends left from the previous post — just a few tips and tricks I found helpful for improving coding efficiency and writing cleaner code.
Lombok
Spring Boot goes great with Lombok!
@Slf4j automatically adds a logger instance to your class, making logging a breeze.
For example, instead of generating all the getters and setters for an Entity via IDE, you can simply use the @Data annotation to generate them all at once. Use @Builder for a fluent builder pattern, and @AllArgsConstructor to automatically generate a constructor with all fields.
In newer versions of Spring, using @Autowired directly on fields triggers a “not recommended” warning. To fix this, simply declare your injected beans as final and add the @RequiredArgsConstructor annotation.
1 |
|
Unified Response Format
It’s a good idea to standardize your response format early in the project. I defined a CommonResponse class to ensure all API responses follow the same structure.
1 | public class CommonResponse<T> { |
Unified Exception Handling
RESTful APIs are supposed to use HTTP status codes to indicate response states.
However, HTTP status codes alone aren’t expressive enough for detailed business logic errors. So I decided to use both HTTP status codes and custom error codes for better clarity.
I used an enum to represent possible error types, each with its own code and httpCode.
Whenever a business error occurs in a service class, just throw new BizException(ErrorType.xxx). The upper layer catches this and extracts the error type to return a proper response to the frontend.
For catching exceptions, I implemented a custom ExceptionHandler:
To handle the httpCode field in CommonResponse, I used a ControllerAdvice to intercept responses and set the HTTP status code accordingly.
1 |
|
This article is licensed under the CC BY-NC-SA 4.0 license.
Author: lyc8503, Article link: https://blog.lyc8503.net/en/post/my-chat-2-backend-misc/
If this article was helpful or interesting to you, consider buy me a coffee¬_¬
Feel free to comment in English below o/