@PostMapping("")
public ResponseEntity<TeamDTO> createTeam(@RequestBody TeamDTO teamDTO) {
TeamDTO savedTeam = teamService.createTeam(teamDTO);
URI location = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(savedTeam.getId())
.toUri();
return ResponseEntity.created(location).build();
}
@PostMapping("/list")
public ResponseEntity<List<TeamDTO>> createTeams(@RequestBody List<TeamDTO> teamDTOList) {
teamService.createTeams(teamDTOList);
URI location = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("")
.build()
.toUri();
return ResponseEntity.created(location).build();
}
@GetMapping("")
public List<TeamDTO> getAllTeams() {
List<TeamDTO> teams = teamService.getAllTeams();
if(teams.isEmpty()) {
throw new TeamNotFoundException("No teams found");
}
return teams;
}
@GetMapping("/{id}")
public TeamDTO getTeam(@PathVariable long id) {
TeamDTO team = teamService.getTeamById(id);
if(team == null) {
throw new TeamNotFoundException("Team not found with id: " + id);
}
return team;
}
package com.chan.ssb.team;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(code = HttpStatus.NOT_FOUND)
public class TeamNotFoundException extends RuntimeException {
public TeamNotFoundException(String message) {
super(message);
}
}
package com.chan.ssb.exception;
import java.time.LocalDate;
public class ErrorDetails {
private LocalDate timestamp;
private String message;
private String details;
public ErrorDetails(LocalDate timestamp, String message, String details) {
this.timestamp = timestamp;
this.message = message;
this.details = details;
}
public LocalDate getTimestamp(){
return this.timestamp;
}
public String getMessage(){
return this.message;
}
public String getDetails(){
return this.details;
}
}
package com.chan.ssb.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import java.time.LocalDate;
@ControllerAdvice
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(LocalDate.now(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
다음과 같다이 없는 id에 출력한다면 잘 따라했다!