Skip to content
Merged

Pjh #157

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,6 @@ public class SecurityConfiguration {
@Value("${jwt.secret}")
private String jwtSecret;

@Bean
@ConditionalOnProperty(name = "spring.h2.console.enabled", havingValue = "true")
public WebSecurityCustomizer configureH2ConsoleEnable() {
return web -> web.ignoring()
.requestMatchers(PathRequest.toH2Console());
}

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
Expand Down Expand Up @@ -102,7 +95,7 @@ public JwtTokenFilter jwtTokenFilter() {
"/admin/**"

// λͺ¨λ“  URL 개방
// ,"/**"
,"/**"
);
return new JwtTokenFilter(jwtSecret, permitAllEndpoints);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import lombok.Getter;

@Getter
public class BadRequestException extends CustomBaseException {
public class BadRequestException extends CustomBaseException {
public BadRequestException(int httpStatus, String message, String code) {
super(message, httpStatus, code);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import lombok.Getter;

@Getter
public class ConflictException extends CustomBaseException {
public class ConflictException extends CustomBaseException {
public ConflictException(int httpStatus, String message, String code) {
super(message, httpStatus, code);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import lombok.Getter;

@Getter
public class NotFoundException extends CustomBaseException {
public class NotFoundException extends CustomBaseException {
public NotFoundException(int httpStatus, String message, String code) {
super(message, httpStatus, code);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import lombok.Getter;

@Getter
public class ServerException extends CustomBaseException {
public class ServerException extends CustomBaseException {
public ServerException(int httpStatus, String message, String code) {
super(message, httpStatus, code);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public class ExceptionCodeMapper {
CONFLICT_MAP.put("ν•΄λ‹Ή λ²€λ”μ˜ ν•΄λ‹Ή μΉ΄ν…Œκ³ λ¦¬ μ†”λ£¨μ…˜μ΄ 이미 μ‘΄μž¬ν•©λ‹ˆλ‹€.", "CONFLICT_EXCEPTION_004");
CONFLICT_MAP.put("같은 μ†”λ£¨μ…˜μ— λ¦¬λ·°λŠ” ν•œ 번만 μž‘μ„±ν•  수 μžˆμŠ΅λ‹ˆλ‹€.", "CONFLICT_EXCEPTION_005");
CONFLICT_MAP.put("이미 ν•΄λ‹Ή 결제 μš”μ²­μ— λŒ€ν•œ 결제 정보가 μ‘΄μž¬ν•©λ‹ˆλ‹€. μƒˆλ‘­κ²Œ 결제 μš”μ²­μ„ μ§„ν–‰ν•΄μ•Όν•©λ‹ˆλ‹€.", "CONFLICT_EXCEPTION_006");
NOT_FOUND_MAP.put("이미 μ‘΄μž¬ν•˜λŠ” μΉ΄ν…Œκ³ λ¦¬μž…λ‹ˆλ‹€.", "CONFLICT_EXCEPTION_007");
CONFLICT_MAP.put("이미 μ‘΄μž¬ν•˜λŠ” μΉ΄ν…Œκ³ λ¦¬μž…λ‹ˆλ‹€.", "CONFLICT_EXCEPTION_007");

// NotFoundException
NOT_FOUND_MAP.put("μ‘΄μž¬ν•˜μ§€ μ•ŠλŠ” 벀더 κΈ°μ—…μž…λ‹ˆλ‹€.", "NOT_FOUND_EXCEPTION_001");
Expand Down Expand Up @@ -71,7 +71,7 @@ public static String getCode(String message, ExceptionType type) {
return switch (type) {
case BAD_REQUEST -> BAD_REQUEST_MAP.getOrDefault(message, "BAD_REQUEST_EXCEPTION_μ˜ˆμ™Έμ½”λ“œ μ„€μ •ν•˜μ„Έμš”.");
case CONFLICT -> CONFLICT_MAP.getOrDefault(message, "CONFLICT_EXCEPTION_μ˜ˆμ™Έμ½”λ“œ μ„€μ •ν•˜μ„Έμš”.");
case NOT_FOUND -> NOT_FOUND_MAP.getOrDefault(message, "NOT_FOUNE_EXCEPTION_μ˜ˆμ™Έμ½”λ“œ μ„€μ •ν•˜μ„Έμš”.");
case NOT_FOUND -> NOT_FOUND_MAP.getOrDefault(message, "NOT_FOUND_EXCEPTION_μ˜ˆμ™Έμ½”λ“œ μ„€μ •ν•˜μ„Έμš”.");
case SERVER -> SERVER_MAP.getOrDefault(message, "SERVER_EXCEPTION_μ˜ˆμ™Έμ½”λ“œ μ„€μ •ν•˜μ„Έμš”.");
case UNAUTHORIZED -> UNAUTHORIZED_MAP.getOrDefault(message, "UNAUTHORIZED_EXCEPTION_μ˜ˆμ™Έμ½”λ“œ μ„€μ •ν•˜μ„Έμš”.");
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,23 @@
@RestControllerAdvice
@RequiredArgsConstructor
public class GlobalExceptionHandler {
// [μˆ˜μ •] ObjectMapperλ₯Ό μΈμŠ€ν„΄μŠ€ λ³€μˆ˜λ‘œ λΆ„λ¦¬ν•˜μ—¬ μž¬μ‚¬μš©μ„± ν–₯상
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private static final String CONTENT_TYPE_JSON = "application/json";
private static final String EMPTY_BODY = "[λ³Έλ¬Έ μ—†μŒ]";
private static final String EXTRACTION_FAILED = "[λ³Έλ¬Έ μΆ”μΆœ μ‹€νŒ¨]";
private static final String UNKNOWN_METHOD = "UNKNOWN";

private final ExceptionLogService exceptionLogService;

@ExceptionHandler({ServerException.class, BadRequestException.class, NotFoundException.class, UnauthorizedException.class, ConflictException.class})
public ResponseEntity<ErrorResponse> handleCustomException(final RuntimeException exception, final HttpServletRequest request) {

if (exception instanceof CustomBaseException ex) {
// [μˆ˜μ •] μŠ€νƒ 트레이슀 쑴재 μ—¬λΆ€ 확인 둜직 κ°œμ„ 
String methodName = ex.getStackTrace().length > 0
? ex.getStackTrace()[0].toString()
: "UNKNOWN";
: UNKNOWN_METHOD;

String requestBody = getRequestBody(request);

Expand All @@ -46,17 +53,18 @@ public ResponseEntity<ErrorResponse> handleCustomException(final RuntimeExceptio
.body(new ErrorResponse(ex.getHttpStatus(), ex.getMessage(), ex.getCode()));
}

// [μˆ˜μ •] 맀직 λ„˜λ²„λ₯Ό μƒμˆ˜λ‘œ 뢄리
final int INTERNAL_SERVER_ERROR_STATUS = 500;
log.error("Unhandled exception caught: ", exception);
return ResponseEntity.status(500)
.body(new ErrorResponse(500, "μ„œλ²„ λ‚΄λΆ€ 였λ₯˜", "INTERNAL_SERVER_ERROR"));
return ResponseEntity.status(INTERNAL_SERVER_ERROR_STATUS)
.body(new ErrorResponse(INTERNAL_SERVER_ERROR_STATUS, "μ„œλ²„ λ‚΄λΆ€ 였λ₯˜", "INTERNAL_SERVER_ERROR"));
}

private String getRequestBody(HttpServletRequest request) {
try {
String contentType = request.getContentType();
ObjectMapper mapper = new ObjectMapper();

if (contentType != null && contentType.contains("application/json")) {
if (contentType != null && contentType.contains(CONTENT_TYPE_JSON)) {
StringBuilder sb = new StringBuilder();
try (BufferedReader reader = request.getReader()) {
String line;
Expand All @@ -65,29 +73,31 @@ private String getRequestBody(HttpServletRequest request) {
}
}

String raw = sb.toString();
if (raw.isBlank()) return "[λ³Έλ¬Έ μ—†μŒ]";
// [μˆ˜μ •] λ³€μˆ˜λͺ… κ°œμ„  (raw -> requestBody)
String requestBody = sb.toString();
if (requestBody.isBlank()) return EMPTY_BODY;

Map<String, Object> json = mapper.readValue(raw, Map.class);
@SuppressWarnings("unchecked")
Map<String, Object> json = OBJECT_MAPPER.readValue(requestBody, Map.class);
Object requestData = json.get("request");

if (requestData instanceof String str) {
try {
Object nested = mapper.readValue(str, Object.class);
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(nested);
Object nested = OBJECT_MAPPER.readValue(str, Object.class);
return OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(nested);
} catch (Exception e) {
return str;
}
}

if (requestData != null) {
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(requestData);
return OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(requestData);
}

return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
return OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(json);
} else {
Map<String, String[]> paramMap = request.getParameterMap();
if (paramMap.isEmpty()) return "[λ³Έλ¬Έ μ—†μŒ]";
if (paramMap.isEmpty()) return EMPTY_BODY;

Map<String, Object> resultMap = new LinkedHashMap<>();
for (Map.Entry<String, String[]> entry : paramMap.entrySet()) {
Expand All @@ -96,10 +106,10 @@ private String getRequestBody(HttpServletRequest request) {
resultMap.put(key, values.length == 1 ? values[0] : Arrays.asList(values));
}

return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(resultMap);
return OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(resultMap);
}
} catch (Exception e) {
return "[λ³Έλ¬Έ μΆ”μΆœ μ‹€νŒ¨]";
return EXTRACTION_FAILED;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,44 +21,53 @@ public class ExceptionLogController {
private final ExceptionLogService exceptionLogService;

@GetMapping()
public String settlement(@RequestParam(defaultValue = "0") int page, @ModelAttribute String errorMessage, Model model) {
int pageSize = 20;
public String getExceptionLogs(@RequestParam(defaultValue = "0") int page, @ModelAttribute String errorMessage, Model model) {
final int pageSize = 20;
int start = page * pageSize;
int end = start + pageSize;

if (start < 0 || end < start) {
model.addAttribute("errorMessage", "잘λͺ»λœ νŽ˜μ΄μ§€ λ²ˆν˜Έμž…λ‹ˆλ‹€.");
model.addAttribute("exceptionLogs", List.of());
model.addAttribute("hasNext", false);
model.addAttribute("currentPage", 0);
model.addAttribute("pageSize", pageSize);
return "log";
}

ObjectMapper objectMapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);

try {
List<ExceptionLogDto> exceptionLogDtos = exceptionLogService.getAllExceptionLogEntity(start, end)
.stream()
.map(dto -> {
String raw = dto.getRequestBody();
String pretty = raw;
// [μˆ˜μ •] λ³€μˆ˜λͺ… κ°œμ„  (raw, pretty -> requestBody, formattedRequestBody)
String requestBody = dto.getRequestBody();
String formattedRequestBody = requestBody;

try {
if (raw != null && raw.trim().startsWith("{")) {
var root = objectMapper.readTree(raw);
if (requestBody != null && !requestBody.trim().isEmpty() && requestBody.trim().startsWith("{")) {
var root = objectMapper.readTree(requestBody);

// case 1: "request" ν‚€κ°€ 있고, κ·Έ 값이 JSON λ¬Έμžμ—΄μ΄λΌλ©΄ β†’ 이쀑 νŒŒμ‹±
if (root.has("request") && root.get("request").isTextual()) {
String nestedStr = root.get("request").asText();

try {
var nestedJson = objectMapper.readTree(nestedStr);
pretty = objectMapper.writerWithDefaultPrettyPrinter()
formattedRequestBody = objectMapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(nestedJson);
} catch (Exception e) {
pretty = nestedStr;
formattedRequestBody = nestedStr;
}

} else {
// case 2: 일반 JSON 객체 β†’ λ°”λ‘œ 예쁘게 좜λ ₯
pretty = objectMapper.writerWithDefaultPrettyPrinter()
formattedRequestBody = objectMapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(root);
}
}
} catch (Exception e) {
// JSON νŒŒμ‹± μ‹€νŒ¨ β†’ 원본 κ·ΈλŒ€λ‘œ
formattedRequestBody = requestBody;
}

return new ExceptionLogDto(
Expand All @@ -67,7 +76,7 @@ public String settlement(@RequestParam(defaultValue = "0") int page, @ModelAttri
dto.getErrorCode(),
dto.getMessage(),
dto.getRequestUri(),
pretty,
formattedRequestBody,
dto.getMethodName()
);
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,13 @@ public ExceptionLogEntity saveExceptionLogEntity(ExceptionLogEntity exceptionLog
public List<ExceptionLogEntity> findAll(int start, int end) {
QExceptionLogEntity qExceptionLogEntity = QExceptionLogEntity.exceptionLogEntity;

int limit = Math.max(0, end - start);

return queryFactory
.selectFrom(qExceptionLogEntity)
.orderBy(qExceptionLogEntity.createdAt.desc())
.offset(start)
.limit(end - start)
.offset(Math.max(0, start))
.limit(limit)
.fetch();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import startwithco.startwithbackend.log.domain.ExceptionLogEntity;
import startwithco.startwithbackend.log.dto.ExceptionLogDto;
import startwithco.startwithbackend.log.repository.ExceptionLogEntityRepository;
Expand All @@ -14,6 +15,7 @@
public class ExceptionLogService {
private final ExceptionLogEntityRepository exceptionLogEntityRepository;

@Transactional
public void saveExceptionLogEntity(int status, String code, String message, String uri, String methodName, String logDetail) {
ExceptionLogEntity exceptionLogEntity = ExceptionLogEntity.builder()
.httpStatus(status)
Expand All @@ -27,6 +29,7 @@ public void saveExceptionLogEntity(int status, String code, String message, Stri
exceptionLogEntityRepository.saveExceptionLogEntity(exceptionLogEntity);
}

@Transactional(readOnly = true)
public List<ExceptionLogDto> getAllExceptionLogEntity(int start, int end) {
return exceptionLogEntityRepository.findAll(start, end).stream()
.map(log -> new ExceptionLogDto(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
package startwithco.startwithbackend.payment.payment.repository;

import io.lettuce.core.dynamic.annotation.Param;
import org.springframework.data.repository.query.Param;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import startwithco.startwithbackend.payment.payment.domain.PaymentEntity;
import startwithco.startwithbackend.payment.paymentEvent.domain.PaymentEventEntity;

import java.util.Optional;

Expand All @@ -21,7 +20,7 @@ WHEN COUNT(p) = 0 THEN true
AND p.paymentEventEntity.paymentEventSeq = :paymentEventSeq
AND p.paymentStatus = 'IN_PROGRESS'
""")
boolean canApproveTossPayment(@Param("orderId") String orderId, Long paymentEventSeq);
boolean canApproveTossPayment(@Param("orderId") String orderId, @Param("paymentEventSeq") Long paymentEventSeq);

@Query("""
SELECT p
Expand Down Expand Up @@ -51,7 +50,7 @@ SELECT COUNT(p)
WHERE p.paymentEventEntity.vendorEntity.vendorSeq = :vendorSeq
AND p.paymentStatus = 'SETTLED'
""")
Long countSETTLEDStatusByVendorSeq(Long vendorSeq);
Long countSETTLEDStatusByVendorSeq(@Param("vendorSeq") Long vendorSeq);

@Query("""
SELECT p
Expand Down
Loading
Loading