반응형
package com.lsj.blog;
import java.util.Random;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.lsj.blog.model.RoleType;
import com.lsj.blog.repository.UserRepository;
import com.lsj.dto.ResponseDto;
@RestController
public class DummyController {
@Autowired // DI
private UserRepository userRepository;
@PostMapping("/api/user")
@Transactional
public ResponseDto<String> save(@RequestBody BlogUser user){
BlogUser usre2 = new BlogUser();
Random random = new Random();
usre2.setUsername(String.valueOf(random.nextInt(10)));
usre2.setPassword("12345");
usre2.setEmail("abc@naver.com");
userRepository.save(usre2);
new ResponseDto<String>(HttpStatus.OK.value(), "데이터 insert에 성공했습니다.");
// HttpStatus.OK.value() → 200이라는 코드 반환 (정상 성공)
}
}
package com.lsj.blog.handler;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import com.lsj.dto.ResponseDto;
@ControllerAdvice // 어떤 Exception이 오든 이 페이지로 오게 된다.
@RestController
public class GlobalExceptionHandler {
@ExceptionHandler(value=Exception.class) // 모든 부모 Exception
public ResponseDto<String> handleException(Exception e) {
return new ResponseDto<String>(HttpStatus.INTERNAL_SERVER_ERROR.value(),e.getMessage());
// HttpStatus.INTERNAL_SERVER_ERROR.value() → 500 코드 반환 (서버 에러)
//return "<h1>" + e.getMessage() + "</h1>";
}
}
package com.lsj.dto;
import org.springframework.http.HttpStatus;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class ResponseDto<T> {
int status;
// HttpStatus status;
T data;
}
반응형