Open jurogrammer opened 2 months ago
현업에서도 이와 유사하게 개발함
https://chatgpt.com/share/3605558e-affd-4ce5-ab35-4351fb43f09a
// BadRequestException.java
public class BadRequestException extends RuntimeException {
public BadRequestException(String message) {
super(message);
}
}
// InternalServerErrorException.java
public class InternalServerErrorException extends RuntimeException {
public InternalServerErrorException(String message) {
super(message);
}
}
// UserController.java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@GetMapping("/user")
public String getUserByEmail(@RequestParam String email) {
if (email == null || email.isEmpty()) {
throw new BadRequestException("User email is not provided.");
}
// For demonstration, let's throw an InternalServerErrorException for some other condition
if ("internal_error@example.com".equals(email)) {
throw new InternalServerErrorException("Internal server error occurred.");
}
return "User email is: " + email;
}
}
// GlobalExceptionHandler.java
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(BadRequestException.class)
public ResponseEntity<ErrorResponse> handleBadRequestException(BadRequestException ex) {
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST.value(), ex.getMessage());
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(InternalServerErrorException.class)
public ResponseEntity<ErrorResponse> handleInternalServerErrorException(InternalServerErrorException ex) {
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), ex.getMessage());
return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
// ErrorResponse.java
public class ErrorResponse {
private int statusCode;
private String message;
public ErrorResponse(int statusCode, String message) {
this.statusCode = statusCode;
this.message = message;
}
// Getters and setters
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
문제
사용자가 잘못 입력하면 고칠 수 있도록 적절한 에러 응답을 보내줘야 하는데 단순히 login page 로 이동
조치
A. 이메일이 없으면 이메일이 없다고 에러 응답. B. 또는 해킹 시도를 차단하기 위해 서버에서는 에러 응답만 보내기. 메일이 없다고 응답받으면 다른 메일로 해킹 시도할테니
오늘의 집 예시
보통 개발했던 플로우
client -> api server: 로그인 요청 api server: 아이디가 없을 경우 throw CustomException(ErrorCode, message) 등 던짐 api server: ExceptionAdviser에서 에러 캐치 및 적절한 에러 응답으로 변환 api server -> client: 에러 응답 전달