无法在Controller中调试@ExceptionHandlerConstraintViolationException.class-Spring Boot

问题描述

有什么方法可以调试如下所示的异常处理程序,从邮递员传递无效请求不会导航到异常处理程序方法

@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类。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...