728x90
반응형

전 포스트에서 만든 공통 응답객체를 활용해서 모든 컨트롤러에서 발생하는 에러를 핸들링해보자.

 

1. CustomRuntimeException

backend/exception/CustomRuntimeException

package web.backend.exception;

public class CustomRuntimeException extends RuntimeException {
    public CustomRuntimeException() {
    }

    public CustomRuntimeException(String message) {
        super(message);
    }

    public CustomRuntimeException(String message, Throwable cause) {
        super(message, cause);
    }

    public CustomRuntimeException(Throwable cause) {
        super(cause);
    }

    public CustomRuntimeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

 

2. ExControllerAdvice

backend/advice/ExControllerAdvice

package mobile.backend.advice;

import lombok.extern.slf4j.Slf4j;
import mobile.backend.exception.CustomRuntimeException;
import mobile.backend.response.CommonResponse;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.NoSuchElementException;

@Slf4j
@RestControllerAdvice(annotations = RestController.class)
public class ExControllerAdvice {

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    @ExceptionHandler
    public CommonResponse<String> exHandle(Exception e) {
        log.error("[exceptionHandle] ex", e);
        return new CommonResponse<String>(false, "시스템 오류");
    }

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler
    public CommonResponse<String> customExHandler(CustomRuntimeException e) {
        log.error("[exceptionHandle] ex", e);
        return new CommonResponse<>(false, e.getMessage());
    }

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler
    public CommonResponse<String> customExHandler(NoSuchElementException e) {
        log.error("[exceptionHandle] ex", e);
        return new CommonResponse<>(true, null);
    }
}

 


테스트

Service에서 임의로 에러를 던져보자.

backend/module/user/UserController

@GetMapping
    public CommonResponse<List<User>> findAll() throws Exception {
        return new CommonResponse<List<User>>(true, userService.findAll());
    }

 

backend/module/user/UserService

    public List<User> findAll() throws Exception {
        throw new Exception();
//        return userSpringJPARepository.findAll();
    }
    
        public String save(User user) {
        throw new CustomRuntimeException("요청이 잘못됨");
//        userSpringJPARepository.save(user);
//        return "ok";
    }

 

1. GET Method ( findAll )

 

2. POST Method ( save )

 

원하는 에러 메세지가 정상적으로 출력되었다.

728x90
반응형

+ Recent posts