Unable to debug @ExceptionHandler(ConstraintViolationException.class) in Controller - Spring boot

280 views Asked by At

Is there any way to debug the exception handler shown below, passing invalid request from postman doesn't navigates to the exception handler method?

@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);
    }

}

Passing invalid request doesn't show the validation errors in the response.,

1

There are 1 answers

0
Murugan On
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;

}

Added the Employee Dto class used for reference.,