Home > database >  Negative scenario for service post method
Negative scenario for service post method

Time:10-14

I have post method in Service. If student age > 18, then I want to save object. If age < 18 .. I don't want to save object.

How can I pass this information to Controller (ResponseEntity) to throw 401?

@Service
public class StudentService {
  public Student save(Student Student) {

    //some logic

    if (studentAge > 20) {
      student.setId(null);
      return studentRepository.save(student);
    } else {
      //what are the good practices here?
    }
  }
}

CodePudding user response:

First of all, you shouldn't return 401 on this case. 401 indicates authentication issue. 400 seems more suitable.

Second thing, the service should not handle error codes - this should be handled by the controller. the service should indicate there's a problem, and the layer using it should decide what to do. It can either be by returning null student or throwing some dedicated exception.
A cleaner approach can be to do it outside of the save method - to have a validator with boolean isValid() method that will be called before saving

  • Related