问题描述
有什么方法可以调试如下所示的异常处理程序,从邮递员传递无效请求不会导航到异常处理程序方法?
@RequestMapping("api/v1/employee")
@RestController
public class EmployeeController {
private final EmployeeService employeeService;
public EmployeeController(EmployeeService employeeService) {
this.employeeService = employeeService;
}
@GetMapping({"/{empId}"})
public ResponseEntity<EmployeeDto> getEmployeeById(@PathVariable("empId") UUID empId) {
return new ResponseEntity<>(employeeService.getEmployeeById(empId),HttpStatus.OK);
}
@SuppressWarnings({ "rawtypes","unchecked" })
@PostMapping
public ResponseEntity createEmployee(@Valid @RequestBody EmployeeDto employeeDto) {
EmployeeDto savedEmployeeDto = employeeService.saveNewEmployee(employeeDto);
HttpHeaders headers = new HttpHeaders();
headers.add("Location","api/v1/employee/" + savedEmployeeDto.getId().toString());
return new ResponseEntity(headers,HttpStatus.CREATED);
}
@SuppressWarnings({ "rawtypes"})
@PutMapping({"/{empId}"})
public ResponseEntity updateEmployee(@PathVariable("empId") UUID empId,@Valid @RequestBody EmployeeDto employeeDto) {
employeeService.updateEmployee(empId,employeeDto);
return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED);
}
@DeleteMapping({"/{empId}"})
@ResponseStatus(HttpStatus.NOT_IMPLEMENTED)
public void deleteEmployee(@PathVariable("empId") UUID empId){
employeeService.deleteEmployeeById(empId);
}
@ExceptionHandler(ConstraintViolationException.class)
private ResponseEntity<List<String>> validationErrorHandler(ConstraintViolationException ex) {
List<String> validationErrors = new ArrayList<>(ex.getConstraintViolations().size());
ex.getConstraintViolations().forEach(violation -> {
validationErrors.add(violation.getPropertyPath() + "_" + violation.getMessage());
});
return new ResponseEntity<>(validationErrors,HttpStatus.BAD_REQUEST);
}
}
解决方法
public class EmployeeDto {
@Null
private UUID id;
@Null
private Integer version;
@NotBlank
private String name;
@Min(18) @Max(60)
private Integer age;
@Null
private OffsetDateTime createdDate;
@Null
private OffsetDateTime lastModifiedDate;
@NotNull
private OffsetDateTime joiningDate;
@NotNull
private EmployeeType employeeType;
@NotNull
@Positive
private BigDecimal salary;
}
添加了用于参考的Employee Dto类。