Home > Enterprise >  Java Springboot exception handling, Get exceptions all at ones
Java Springboot exception handling, Get exceptions all at ones

Time:08-12

This is my Controller class and I wrote exceptions to check pin and username(because I want to make them unique) But When I enter data in Postman It gives only one of them( I want to create scenario that both pin and username are not unique and used for once) How can I write Both of them same time. I actually want to add some elements additionally like that so I'm stuck there) I want output be like: Ex: This pin Already in use! This username Already in use!

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

    }

}

CodePudding user response:

You should define a class with attribute like private List<String> errMsg to handle response

Then, check pin and username and save check result to boolean variable. If result are false, add an element to errMsg like "pin already in use", "username already in use".

Finally, dependent to check results, if all of them are false, you can throw PinAndUsernameAlreadyExistsException with errMsg have 2 messages were added

CodePudding user response:

If you need all the fields in the exception message don't throw the exception until all validations have been made, however for a public accessed application is not a good idea from a security perspective, It's better a generic error message like: "Some of your employee data is already used", anyway, if you need it for some kind of customer requirement or simple formation exercise, this code should do what you ask for:


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

}
  • Related