Skip to content

Commit

Permalink
Feat: 에러 발생 시 CORS 설정 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
pjh5365 committed Nov 19, 2024
1 parent 1a3c142 commit a55e836
Showing 1 changed file with 12 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

/**
Expand All @@ -18,15 +19,24 @@
@RestControllerAdvice
public class ControllerAdvice {

private void addCorsHeaders(HttpServletResponse response) {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
response.setHeader("Access-Control-Allow-Credentials", "true");
}

@ExceptionHandler(Exception.class)
public ResponseEntity<ApiResponse<String>> common(Exception e) {
public ResponseEntity<ApiResponse<String>> common(Exception e, HttpServletResponse response) {
addCorsHeaders(response); // CORS 헤더 추가
log.error("[밥상일터]: 예상치 못한 예외가 발생하였습니다. 예외내용 = {}", e.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(ApiResponse.failure("관리자에게 문의해주세요."));
}

@ExceptionHandler({IllegalArgumentException.class, AccessDeniedException.class})
public ResponseEntity<ApiResponse<String>> illegalArgument(Exception e) {
public ResponseEntity<ApiResponse<String>> illegalArgument(Exception e, HttpServletResponse response) {
addCorsHeaders(response); // CORS 헤더 추가
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(ApiResponse.failure(e.getMessage()));
}
Expand Down

0 comments on commit a55e836

Please sign in to comment.