[Start Spring Boot] HTTP 상태코드와 예외처리

·2024년 3월 19일
0

Start Spring Boot!

목록 보기
18/53
post-thumbnail

HTTP 상태코드

번호대별 정리

  • 1XX: Informational(정보 제공)
  • 2XX: Success(성공)
  • 3XX: Redirection(리다이렉션)
  • 4XX: Client Error(클라이언트 에러)
  • 5XX: Server Error(서버 에러)

Success

  • 200: OK / 서버가 요청을 성공적으로 처리
  • 201: Created / 요청이 처리되어서 새로운 리소스가 생성됨
  • 202: Accepted / 요청은 접수하였지만, 처리가 완료되지 않음

Redirection

  • 301: Moved Permanently / 지정한 리소스가 새로운 URI로 이동함
  • 303: See Other / 다른 위치로 요청해라

Client Error

  • 400: Bad Request / 요청의 구문이 잘못됨
  • 401: Unauthorized / 권한이 없음
  • 403: Forbidden / 지정한 리소스에 대한 액세스가 금지
  • 404: Not Found / 지정한 리소스를 찾을 수 없음

Server Error

  • 500: Internal Server Error / 서버에 에러가 발생
  • 501: Not Implemented / 요청한 URI의 메소드에 대해 서버가 구현 안됨
  • 502: Bad Gateway / 게이트웨이 또는 프록시 역할을 하는 서버가 그 뒷단의 서버로부터 잘못된 응답을 받음

응답코드 만들어서 반환하기

    @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();

    }
    
  • 다음과 같이 ResponseEntity를 이용해서 응답코드를 반환할 수 있다.
  • 201의 경우 location 정보를 담아서 보낼 수 있다.

예외처리

  • 해당 리소스가 존재하지 않을 때, 지금은 null을 리턴하고 있다. 다음을 수정해보자

Controller에서 예외 발생시키기

    @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;
    }
    
  • 다음과 같이 throw를 이용해서 예외를 발생시킬 수 있다.

예외처리 클래스 만들기

  • TeamNotFoundException.java
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);
    }
}
  • @ResponseStatus: 다음을 통해 발생시킬 HTTP 상태코드를 정한다. 404를 반환하였다.
  • RuntimeException: 실행중에 발생하는 모든 예외를 위한 것

예외처리의 범위를 늘려보자!

  • 다음을 통해 모든 예외를 처리해보자

예외처리반환 클래스 만들기

  • ErrorDetails.java
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;
    }

}

사용자 정의 ResponseEntityExceptionHandler 구현하기

  • CustomizedResponseEntityExceptionHandler.java
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);
    }
}
  • @ControllerAdvice: 모든 컨트롤러에서 발생하는 예외를 잡아준다.
  • @ExceptionHandler(Exception.class): Controller계층에서 발생하는 에러를 잡아서 메서드로 처리해주는 기능 / 인자의 클래스를 이용


다음과 같다이 없는 id에 출력한다면 잘 따라했다!

profile
백엔드 개발자가 꿈인 컴공과

0개의 댓글

관련 채용 정보