본문 바로가기
[패스트캠퍼스] Spring

패스트캠퍼스 챌린지 30일차

by 엑츄얼리 2022. 2. 22.

Part 1. Spring Framework

 Ch 04. 예외처리

  01. 예외처리를 제대로 안했을 때의 문제점_01

   - 반복적이고 불필요한 예외를 방지하기 위해 exception을 각 컨트롤러에서 처리하는게 아닌,

     GlobalExceptionController라는 새로운 예외처리컨트롤러를 생성하여 일괄 처리

package com.fastcampus.programmin.dmaker.exception;

import com.fastcampus.programmin.dmaker.dto.DMakerErrorResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestControllerAdvice //bean으로 등록하기 위한 Annotation, ExceptionHandler

public class DMakerExceptionHandler {
    @ExceptionHandler(DMakerException.class)
    public DMakerErrorResponse handleException(
            DMakerException e,
            HttpServletRequest request
    ) {
        log.error("errorCode : {}, url: {}, message : {}", e.getDMakerErrorCode(), e.getDetailMessage());

        return DMakerErrorResponse.builder()
                .errorCode(e.getDMakerErrorCode())
                .errorMessage(e.getDetailMessage())
                .build();
    }

    @ExceptionHandler(value = {
            HttpRequestMethodNotSupportedException.class,
            MethodArgumentNotValidException.class
    })

    public DMakerErrorResponse handleBadRequest(
            Exception e, HttpServletRequest request
    ){
        log.error("url: {}, message : {}", e.getMessage());

        return DMakerErrorResponse.builder()
                .errorCode(DMakerErrorCode.INVALID_REQUEST)
                .errorMessage(DMakerErrorCode.INVALID_REQUEST.getMessage())
                .build();
    }

    @ExceptionHandler(Exception.class)

    public DMakerErrorResponse handleException(
            Exception e, HttpServletRequest request
    ){
        log.error("url: {}, message : {}", e.getMessage());

        return DMakerErrorResponse.builder()
                .errorCode(DMakerErrorCode.INTERNAL_SERVER_ERROR)
                .errorMessage(DMakerErrorCode.INTERNAL_SERVER_ERROR.getMessage())
                .build();
    }
}

<DMakerExceptionHandler.java>

 

-----------------------------------------------------------------------------------------------------------------------------------------

https://bit.ly/37BpXic

댓글