feat(common): add exception handling and response utilities
backend project initial!!!
This commit is contained in:
@@ -13,6 +13,9 @@ dependencies {
|
||||
// Test
|
||||
testImplementation("org.springframework.boot:spring-boot-starter-test")
|
||||
|
||||
// jsr380
|
||||
implementation("org.springframework.boot:spring-boot-starter-validation")
|
||||
|
||||
// 其他依赖…
|
||||
implementation(project(":weblog-module-common"))
|
||||
implementation(project(":weblog-module-admin"))
|
||||
|
||||
@@ -3,19 +3,36 @@ package com.hanserwei.web.controller;
|
||||
import com.hanserwei.common.aspect.ApiOperationLog;
|
||||
import com.hanserwei.web.model.User;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.validation.FieldError;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@RestController
|
||||
@Slf4j
|
||||
public class TestController {
|
||||
|
||||
@PostMapping("/test")
|
||||
@ApiOperationLog(description = "测试接口")
|
||||
public User test(@RequestBody User user) {
|
||||
public ResponseEntity<String> test(@RequestBody @Validated User user, BindingResult bindingResult) {
|
||||
// 是否存在校验错误
|
||||
if (bindingResult.hasErrors()) {
|
||||
// 获取校验不通过字段的提示信息
|
||||
String errorMsg = bindingResult.getFieldErrors()
|
||||
.stream()
|
||||
.map(FieldError::getDefaultMessage)
|
||||
.collect(Collectors.joining(", "));
|
||||
|
||||
return ResponseEntity.badRequest().body(errorMsg);
|
||||
}
|
||||
|
||||
// 返参
|
||||
return user;
|
||||
return ResponseEntity.ok("参数没有任何问题");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,11 +1,25 @@
|
||||
package com.hanserwei.web.model;
|
||||
|
||||
import jakarta.validation.constraints.*;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class User {
|
||||
// 用户名
|
||||
// 用户名
|
||||
@NotBlank(message = "用户名不能为空") // 注解确保用户名不为空
|
||||
private String username;
|
||||
// 性别
|
||||
@NotNull(message = "性别不能为空") // 注解确保性别不为空
|
||||
private Integer sex;
|
||||
|
||||
// 年龄
|
||||
@NotNull(message = "年龄不能为空")
|
||||
@Min(value = 18, message = "年龄必须大于或等于 18") // 注解确保年龄大于等于 18
|
||||
@Max(value = 100, message = "年龄必须小于或等于 100") // 注解确保年龄小于等于 100
|
||||
private Integer age;
|
||||
|
||||
// 邮箱
|
||||
@NotBlank(message = "邮箱不能为空")
|
||||
@Email(message = "邮箱格式不正确") // 注解确保邮箱格式正确
|
||||
private String email;
|
||||
}
|
||||
Reference in New Issue
Block a user