티스토리 뷰

api 예외처리를 위해 간단히 api컨트롤러를 만들었다.

 

package hello.exception.api;


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
public class ApiExceptionController {

    @GetMapping("/api/members/{id}")
    public MemberDto getMember(@PathVariable("id")String id){
        if(id.equals("ex")){
            throw new RuntimeException("잘못된 사용자");
        }
        return new MemberDto(id, "hello" + id);
    }

    @Data
    @AllArgsConstructor
    static class MemberDto{
        private String memberId;
        private String name;
    }

}

 

포트스맨으로 요청하면 다음과 같이 제대로 작동하고 있다. 이번엔 오류를 발생시켜 본다.

 

RuntimeException의 값으로 html이 결과로 나왔다. api의 에러 값은 이래선 안된다. 실패메세지를 가져와야 할 것이다. 현재는 내가 설정해둔 에러페이지를 그대로 뱉고 있다. 독립적인 프로젝트에서 쓰는 것이 아니고 상호간의 통신을 위한 것이므로 실패값을 던져주어 상대방도 그에 맞는 적절한 조취를 취할 수 있다.

 

일단 요청할 때에 request Header에 Accept가 application/json인 것에 주목하자.  컨트롤러도 그에 맞게 호출한다.

 

    @RequestMapping("/error-page/500")
    public String errorPage500(HttpServletResponse response, HttpServletRequest request){
        printErrorInfo(request);
        log.info("errorPage 500");
        return "error-page/500";
    }

    @RequestMapping(value="/error-page/500", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Map<String,Object>> errorPage500Api(
            HttpServletRequest request, HttpServletResponse response){
        log.info("API errorPage 500");

        Map<String, Object> result = new HashMap<>();
        Exception ex = (Exception) request.getAttribute(ERROR_EXCEPTION);
        result.put("status", request.getAttribute(ERROR_STATUS_CODE));
        result.put("message",ex.getMessage());

        Integer statusCode = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);

        return new ResponseEntity<>(result, HttpStatus.valueOf(statusCode));
    }

 

이러 컨트롤러를 만들 때에 produces 속성을 통해 json 요청일 경우 아래의 컨트롤러로 가게 된다.

 

이제 등록을 해준다.

 

package hello.exception;

import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

@Component
public class WebServerCustomizer implements WebServerFactoryCustomizer<ConfigurableWebServerFactory> {

    @Override
    public void customize(ConfigurableWebServerFactory factory) {
        ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/error-page/404");
        ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error-page/500");

        ErrorPage errorPageEx = new ErrorPage(RuntimeException.class, "/error-page/500");
        //런타임 또는 그 자식 타입의 에러일 경우 500 (500 예외가 서버내부에서 발생한 오류라는 뜻을 포함하고 있기 때문에 여기서는 예외가
        //발생한 경우도 500 오류 화면으로 처리했다.
        factory.addErrorPages(errorPage404,errorPage500,errorPageEx);

    }
}

 

errorPageEx를 보면 RuntimeException 일때에 해당 컨트롤러로 이동하게 되어있다.

다음과 같은 결과가 나온다. 저 메세지는 어디에서 왔냐고?

 

package hello.exception.api;


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
public class ApiExceptionController {

    @GetMapping("/api/members/{id}")
    public MemberDto getMember(@PathVariable("id")String id){
        if(id.equals("ex")){
            throw new RuntimeException("잘못된 사용자");
        }
        return new MemberDto(id, "hello" + id);
    }

    @Data
    @AllArgsConstructor
    static class MemberDto{
        private String memberId;
        private String name;
    }

}

 

처음 컨트롤러를 만들 때에 이미 메세지를 심어 놨었다.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함