에러 api 생성하는 방법

su dong·2023년 7월 7일
0

컨트롤러를 통해서 특정 url요청에 응답할 때, 불가능한 요청이 들어오는 경우 메서드를 매핑해주는 대신에 예외처리를 해준다.

Controller

@GetMapping("/order/{orderId}")
    public String getOrder2(@PathVariable String orderId) throws IllegalAccessException {
        log.info("orderId : {}", orderId);
        if ("500".equals(orderId)) {
            throw new IllegalAccessException("500 is not valid orderId");
        }
        return "orderId : " + orderId ;
    }

@ExceptionHandler(WebSampleException.class)
public ResponseEntity<ErrorResponse> handleWebSampleException(WebSampleException e) {
        String exceptionMessage = e.getMessage();
        log.error("WebSampleException is occurred: {}", exceptionMessage, e);

        return ResponseEntity
                .status(HttpStatus.FORBIDDEN)
                .body(new ErrorResponse(e.getErrorCode(),"WebSampleException is occurred: " + exceptionMessage));
    }

위 코드는 WebSampleException이 발생했을 때 처리해주는 코드로, 반환값은 ErrorResponse(에러코드, 에러 메세지)를 요소로 가지는 ResponseEntity가 된다.
ResponseEntity에 status와 body값을 지정할 수 있다.

error Dto

package WebSample.demo.dto;

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class ErrorResponse {
    private String errorCode;
    private String message;
}

에러는 스트링으로 반환할 수도 있고, 위와 같이 특정 dto를 통해서 반환할 수도 있다.

하지만 위 코드는 controller마다 예외 코드를 작성해줘야 하는 중복이 생긴다.
이를 해결하기 위해서 exception 폴더 하위에 GlobalExceptionHandler 클래스를 생성해서 프로그램 전역적으로 예외 처리를 해줄 수 있다.

exception/GlobalExceptionHandler.java

package WebSample.demo.exception;

import WebSample.demo.dto.ErrorResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(WebSampleException.class)
    public ResponseEntity<ErrorResponse> handleWebSampleException(WebSampleException e) {
        String exceptionMessage = e.getMessage();
        log.error("WebSampleException is occurred: {}", exceptionMessage, e);

        return ResponseEntity
                .status(HttpStatus.FORBIDDEN)
                .body(new ErrorResponse(e.getErrorCode(),"WebSampleException is occurred: " + exceptionMessage));
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponse> handleException(Exception e) {
        String exceptionMessage = e.getMessage();
        log.error("Exception is occurred: {}", e);

        return ResponseEntity
                .status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(new ErrorResponse(ErrorCode.INTERNAL_SERVER_ERROR,"WebSampleException is occurred: " + exceptionMessage));

    }

}
profile
사람들을 돕는 문제 해결사, 개발자 sudong입니다. 반갑습니다. tkddlsqkr21@gmail.com

0개의 댓글