POST /api/memos { "title": "", ... }
PUT /api/memos/{id} { "title": " ", ... }
Postman으로 빈 title내면 DB까지 안 가고 400으로 막는다.
Vue 화면 검증과 별개로, API만 직접 호출해도 검증되게 만든다.
| Vue 검증 | Spring 검증 | |
|---|---|---|
| 막는 대상 | 화면에서 저장 버튼 | Postman / 다른 클라이언트 |
| 응답 | toast warning | 400 + JSON |
프론트만 있으면 API를 직접 호출하면 빈 title이 들어갈 수 있다.
public class MemoValidationException extends RuntimeException {
public MemoValidationException(String message) {
super(message);
}
}
검증 실패 시 Service에서 throw 하는 전용 예외
public void insertMemo(String title, String content, String status) {
validateTitle(title);
// ... insert
}
public void updateMemo(int id, String title, String content, String status) {
validateTitle(title);
// ... update
}
private void validateTitle(String title) {
if (title == null || title.trim().isEmpty()) {
throw new MemoValidationException("title은 필수입니다");
}
}
@RestControllerAdvice
public class MemoApiExceptionHandler {
@ExceptionHandler(MemoValidationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String, String> handleValidation(MemoValidationException e) {
Map<String, String> error = new HashMap<>();
error.put("message", e.getMessage());
return error;
}
}
| 어노테이션 | 역할 |
|---|---|
@RestControllerAdvice | API 예외 공통 처리 |
@ExceptionHandler | 이 예외 잡기 |
@ResponseStatus(BAD_REQUEST) | HTTP 400 |
응답 예:
{ "message": "title은 필수입니다" }
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
<context:include-filter type="annotation"
expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
Create (400)
POST http://localhost:8080/playground/api/memos
{ "title": "", "content": "내용", "status": "READY" }
Update (400)
PUT http://localhost:8080/playground/api/memos/1
{ "title": " ", "content": "내용", "status": "READY" }
정상 (200)
{
"title": "제목",
"content": "내용",
"status": "READY"
}
POST / PUT 시 title 빈값 → 400 Bad Request{ "message": "title은 필수입니다" }Controller: @RequestBody MemoVO
→ Service: validateTitle() → 실패 시 MemoValidationException
→ MemoApiExceptionHandler: 400 + message JSON
MemoValidationException 추가validateTitle() (insert / update)MemoApiExceptionHandler (@RestControllerAdvice)dispatcher-servlet.xml에 ControllerAdvice 스캔@RequestParam + XML <if>