Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- 카카오로그인
- 객체
- nextjs
- DB
- JavaScript
- nestjs
- 캐러셀
- 위크맵
- 위크셋
- 이메일 전송
- Map
- 중첩 구조 분해
- 화살표 함수
- AGGREGATE
- JSON.parse
- context switch
- logstash
- nodemailer
- react-slick
- 로그스태시
- Mongoose
- nest
- 카카오 소셜로그인
- TypeScript
- 구조 분해 할당
- JSON.stringify
- 참조에 의한 객체 복사
- javacript
- 자바스크립트
- MongoDB
Archives
- Today
- Total
뚜sh뚜sh
Spring 예외 처리 구현 본문
1. 사용자 정의 에러 응답 클래스 생성
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@Getter
@RequiredArgsConstructor
public class ErrorResponse {
private final int errorCode;
private final String errorMessage;
}
2. @ControllerAdvice를 사용한 전역 예외 처리기 구현
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(DuplicateException.class)
public ResponseEntity<ErrorResponse> handleDuplicateException(DuplicateException e) {
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.CONFLICT.value(), e.getMessage());
return new ResponseEntity<>(errorResponse, HttpStatus.CONFLICT);
}
}
- '@ControllerAdvice' 어노테이션은 스프링이 예외를 처리하는 클래스임을 나타냄
- '@ExceptionHandler(DuplicateException.class)'는 DuplicateException 타입의 예외를 처리함
- 이 메서드는 예외가 발생했을 때 ErrorResponse 객체를 생성하고, 이를 ResponseEntity로 감싸서 클라이언트에 전달함
3. 사용자 정의 예외 생성
public class DuplicateException extends RuntimeException {
public DuplicateException() {
super();
}
public DuplicateException(String message) {
super(message);
}
public DuplicateException(String message, Throwable cause) {
super(message, cause);
}
public DuplicateException(Throwable cause) {
super(cause);
}
protected DuplicateException(String message, Throwable cause, boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
- 이렇게 설정하면, 애플리케이션에서 'DuplicateException'이 발생할 경우, 'GlobalExceptionHandler'에서 정의한 메서드가 호출되어 클라이언트에게 일관된 에러 응답을 반환하게 됨
'Framework > Spring' 카테고리의 다른 글
비밀번호 유효성 검사를 위한 정규식 (2) | 2024.02.06 |
---|---|
Spring Security로 암호화된 비밀번호 검증하기 (0) | 2024.01.31 |
Spring Security로 비밀번호 암호화 하기 (0) | 2024.01.27 |
Custom Validation Annotation 만들기 (0) | 2024.01.27 |
[ERROR] 컨트롤러에서 JSON으로 데이터 반환할 때 406 에러 발생 (0) | 2024.01.26 |
Comments