
Python實(shí)現(xiàn)動(dòng)圖生成:輕松創(chuàng)建自定義表情包
private boolean success;
private String message;
private T data;
private List<String> errors;
private int errorCode;
private long timestamp; // Adding timestamp for tracking
private String path; // Adding path to identify the API endpoint
// Constructors, getters, and setters
}
boolean
2.消息 :
String
3.數(shù)據(jù):
T
4.錯(cuò)誤 :
List<String>
5. 錯(cuò)誤代碼 :
int
6.時(shí)間戳 :
long
7.路徑 :
String
讓我們創(chuàng)建實(shí)用的方法來生成響應(yīng),以保持不重復(fù)。這樣做既可以確保一致性,又能減少樣板代碼。
public class ResponseUtil {
public static <T> ApiResponse<T> success(T data, String message, String path) {
ApiResponse<T> response = new ApiResponse<>();
response.setSuccess(true);
response.setMessage(message);
response.setData(data);
response.setErrors(null);
response.setErrorCode(0); // No error
response.setTimestamp(System.currentTimeMillis());
response.setPath(path);
return response;
}
public static <T> ApiResponse<T> error(List<String> errors, String message, int errorCode, String path) {
ApiResponse<T> response = new ApiResponse<>();
response.setSuccess(false);
response.setMessage(message);
response.setData(null);
response.setErrors(errors);
response.setErrorCode(errorCode);
response.setTimestamp(System.currentTimeMillis());
response.setPath(path);
return response;
}
public static <T> ApiResponse<T> error(String error, String message, int errorCode, String path) {
return error(Arrays.asList(error), message, errorCode, path);
}
}
我們可以使用 @ControllerAdvice 和 @ExceptionHandler 注解來全局處理異常,確保捕獲任何未處理的錯(cuò)誤并以標(biāo)準(zhǔn)響應(yīng)格式返回。
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<ApiResponse<Void>> handleException(HttpServletRequest request, Exception ex) {
List<String> errors = Arrays.asList(ex.getMessage());
ApiResponse<Void> response = ResponseUtil.error(errors, "An error occurred", 1000, request.getRequestURI()); // General error
return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ApiResponse<Void>> handleResourceNotFoundException(HttpServletRequest request, ResourceNotFoundException ex) {
ApiResponse<Void> response = ResponseUtil.error(ex.getMessage(), "Resource not found", 1001, request.getRequestURI()); // Resource not found error
return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
}
@ExceptionHandler(ValidationException.class)
public ResponseEntity<ApiResponse<Void>> handleValidationException(HttpServletRequest request, ValidationException ex) {
ApiResponse<Void> response = ResponseUtil.error(ex.getErrors(), "Validation failed", 1002, request.getRequestURI()); // Validation error
return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
}
// Handle other specific exceptions similarly
}
現(xiàn)在,讓我們?cè)谑纠刂破髦惺褂脴?biāo)準(zhǔn)化響應(yīng)結(jié)構(gòu)。
@RestController
@RequestMapping("/api/products")
public class ProductController {
@GetMapping("/{id}")
public ResponseEntity<ApiResponse<Product>> getProductById(@PathVariable Long id, HttpServletRequest request) {
// Fetch product by id (dummy code)
Product product = productService.findById(id);
if (product == null) {
throw new ResourceNotFoundException("Product not found with id " + id);
}
ApiResponse<Product> response = ResponseUtil.success(product, "Product fetched successfully", request.getRequestURI());
return new ResponseEntity<>(response, HttpStatus.OK);
}
@PostMapping
public ResponseEntity<ApiResponse<Product>> createProduct(@RequestBody Product product, HttpServletRequest request) {
// Create new product (dummy code)
Product createdProduct = productService.save(product);
ApiResponse<Product> response = ResponseUtil.success(createdProduct, "Product created successfully", request.getRequestURI());
return new ResponseEntity<>(response, HttpStatus.CREATED);
}
// More endpoints...
}
以下是您可能使用的常見錯(cuò)誤代碼的快速參考(這些只是示例,您可以根據(jù)您的項(xiàng)目進(jìn)行自定義):
通過標(biāo)準(zhǔn)化錯(cuò)誤代碼,您可以簡(jiǎn)化跨應(yīng)用程序不同層處理錯(cuò)誤的過程,從而更輕松地管理和調(diào)試問題。這些錯(cuò)誤代碼可以在前端和后端維護(hù),以確保一致的錯(cuò)誤處理并向用戶提供有意義的反饋。
在Spring Boot中,實(shí)施一種清晰、一致的處理API響應(yīng)的方法,不僅能使您的API更加簡(jiǎn)潔和易于維護(hù),而且會(huì)讓您的前端團(tuán)隊(duì)(甚至未來的您)感激不盡。
對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力
一鍵對(duì)比試用API 限時(shí)免費(fèi)