我在服務中有 post 方法。如果學生年齡 > 18,那么我想保存物件。如果年齡 < 18 .. 我不想保存物件。
如何將此資訊傳遞給控制器??(ResponseEntity)以拋出 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?
}
}
}
uj5u.com熱心網友回復:
首先,你不應該在這種情況下回傳 401。401 表示身份驗證問題。400似乎更合適。
第二件事,服務不應該處理錯誤代碼——這應該由控制器處理。服務應該表明存在問題,使用它的層應該決定做什么。它可以是通過回傳空學生或拋出一些專用例外。
一種更簡潔的方法是在 save 方法之外執行此操作 - 使用boolean isValid()將在保存之前呼叫的方法的驗證器
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/314016.html
