Java Springboot异常处理,一次性获取异常



这是我的Controller类,我写了异常来检查pin和username(因为我想让它们唯一(。但当我在Postman中输入数据时,它只给出其中一个(我想创建一个场景,让pin和username都不唯一,只使用一次(我怎么能同时写这两个。我实际上想添加一些额外的元素,所以我被困在那里(我希望输出如下:这个别针已经在用了!此用户名已在使用中!

@RestController
@RequestMapping("/api")
public class EmployeeController {
//private EmployeeService employeeService;
private final EmployeeRepository employeeRepository;
//    ControllerException controllerException;
@Autowired
public EmployeeController(EmployeeRepository employeeRepository) {
this.employeeRepository = employeeRepository;
}
@PostMapping("/employee")
public ResponseEntity<Employee> saveEmployee(@RequestBody Employee employee, BindingResult bindingResult) throws EmployeeAlreadyExistsException {
if (employeeRepository.existsById(employee.getId())) {
throw new EmployeeAlreadyExistsException();
}
String temUsername = employee.getUsername();
if(temUsername !=null && !"".equals(temUsername)) {
Employee userObject = employeeRepository.findByUsername(temUsername);
if(userObject!=null) {
throw new EmployeeUsernameAlreadyExistsException();
}
}
String pin = employee.getPin();
if(pin !=null && !"".equals(pin)) {
Employee userObject = employeeRepository.findByPin(pin);
if(userObject!=null) {
throw new EmployeePinAlreadyExistsException();
}
}

Employee employee1 = employeeRepository.save(employee);
return new ResponseEntity<>(employee1, HttpStatus.CREATED);
}

@GetMapping("/employees")
public ResponseEntity<List<Employee>> getAllEmployee() throws EmployeeNotFoundException {
return new ResponseEntity<>((List<Employee>) employeeRepository.findAll(), HttpStatus.OK);
}
@PostMapping("/update")
public ResponseEntity<?> updateEmployee(@RequestBody Employee employee) throws EmployeeNotFoundException, EmployeePinAlreadyExistsException {
if (!employeeRepository.existsById(employee.getId())) {
throw new EmployeeNotFoundException();
} else {
Employee employee1 = employeeRepository.save(employee);
return new ResponseEntity<>(employee1, HttpStatus.CREATED);
}

}
@GetMapping("employee/{id}")
public ResponseEntity<?> getEmployeeById(@PathVariable("id") int id, Employee employee) throws EmployeeNotFoundException {
if (!employeeRepository.existsById(employee.getId())) {
throw new EmployeeNotFoundException();
}
return new ResponseEntity<>(employeeRepository.findById(id), HttpStatus.OK);
}
@ExceptionHandler(value = EmployeeAlreadyExistsException.class)
public ResponseEntity<?> EmployeeAlreadyExistsException(EmployeeAlreadyExistsException employeeAlreadyExistsException) {
ErrorResponse erResp = ErrorResponse.builder()
.message("This Employee already exist!")
.code("101")
.traceId(UUID.randomUUID().toString())
.build();
return new ResponseEntity<>(erResp, HttpStatus.CONFLICT);
}
@ExceptionHandler(value = EmployeeNotFoundException.class)
public ResponseEntity<?> EmployeeNotFoundException(EmployeeNotFoundException employeeNotFoundException) {
ErrorResponse erResp = ErrorResponse.builder()
.message("This id is not valid!")
.code("404")
.traceId(UUID.randomUUID().toString())
.build();
return new ResponseEntity<>(erResp, HttpStatus.CONFLICT);
}
@ExceptionHandler(value = EmployeePinAlreadyExistsException.class)
public ResponseEntity<?> EmployeePinAlreadyExistsException(EmployeePinAlreadyExistsException employeePinAlreadyExistsException) {
ErrorResponse erResp = ErrorResponse.builder()
.message("This pin Already in use!")
.code("101")
.traceId(UUID.randomUUID().toString())
.build();
return new ResponseEntity<>(erResp, HttpStatus.CONFLICT);
}
@ExceptionHandler(value = EmployeeUsernameAlreadyExistsException.class)
public ResponseEntity<?> EmployeeUsernameAlreadyExistsException(EmployeeUsernameAlreadyExistsException employeeUsernameAlreadyExistsException) {
ErrorResponse erResp = ErrorResponse.builder()
.message("This Username Already in use!")
.code("109")
.traceId(UUID.randomUUID().toString())
.build();
return new ResponseEntity<>(erResp, HttpStatus.CONFLICT);
}
}

您应该定义一个具有private List<String> errMsg等属性的类来处理响应

然后,检查pin和用户名,并将检查结果保存到布尔变量中。如果结果为false,则向errMsg添加一个元素,如";销已在使用中"用户名已在使用中";。

最后,根据检查结果,如果所有结果都为false,则可以抛出带有errMsg的PinAndUsernameAlreadyExistsException,其中添加了2条消息

如果您需要异常消息中的所有字段,在进行所有验证之前不要抛出异常,但是对于公共访问的应用程序来说,从安全角度来看不是一个好主意,最好是一个通用的错误消息,如:"您的一些员工数据已经被使用";,无论如何,如果您需要它来满足某种客户需求或进行简单的信息练习,则此代码应该满足您的要求:


private void assertEmployeeDataisUnique(Employee employee) throws Exception {
List<String> existingFields = new ArrayList<>();
if (employeeRepository.existsById(employee.getId())) {
existingFields.add("id");
}
String temUsername = employee.getUsername();
if(temUsername !=null && !"".equals(temUsername)) {
Employee userObject = employeeRepository.findByUsername(temUsername);
if(userObject!=null) {
existingFields.add("username");
}
}
String pin = employee.getPin();
if(pin !=null && !"".equals(pin)) {
Employee userObject = employeeRepository.findByPin(pin);
if(userObject!=null) {
existingFields.add("pin");
}
}
if(!existingFields.isEmpty()) {
throw new Exception("Employee data is not unique. Fields: " + existingFields);
}
}
@PostMapping("/employee")
public ResponseEntity<Employee> saveEmployee(@RequestBody Employee employee, BindingResult bindingResult) throws EmployeeAlreadyExistsException {
this.assertEmployeeDataisUnique(employee);

Employee employee1 = employeeRepository.save(employee);
return new ResponseEntity<>(employee1, HttpStatus.CREATED);
}

最新更新