Spring API 프로젝트에서 공통적인 에러 코드로 응답하기.

 

API 개발시 어떠한 처리 결과에도 동일한 포맷의 응답(response) 을 리턴하는 것은 중요하다. 아래는 가장 간단한 예이다.

 

{
    "code": 200,
    "message": "ok",
    "result": {}
}

 

code / message 로 미리 정의된 응답 코드와 메시지를 확인할 수 있고, 정상적으로 처리가 되었을 경우 result 에서 결과를 확인할 수 있다. 디테일이 필요하다면 더 다양한 코드에 상세한 설명을 넣으면 되고, 보안을 강화한다면 메시지를 없앨 수도 있다. 이러한 공통적인 포맷을 Spring 에서 구현하는 방법을 살펴 보았다.

 

 

1. whitelabel 에러 페이지

 

Spring Boot 는 기본적으로 text/html 타입의 요청에 대해 whitelabel 이라는 오류 페이지를 제공한다. 기존 톰캣의 보라색 에러 페이지 보다는 괜찮아 보일 수 있다.

 

 

whitelabel-spring

 

브라우저에서 접속했을 때에도 에러 페이지를 커스텀 하려면 properties 파일에서 whitelabel 페이지를 비활성화 하고 에러 페이지를 재정의해야 한다.

 

# application.properties
server.error.whitelabel.enabled=false

 

 

2. 기본 json 에러 응답

 

Spring Boot 는 기본적으로 RESTful 이나 application/json 타입의 요청에 대해 basicErrorController 로부터 아래와 같은 포맷으로 응답한다.

 

{
    "timestamp": "2022-02-15T04:28:46.310+00:00",
    "status": 404,
    "error": "Not Found",
    "path": "/a"
}

 

위 속성은 DefaultErrorAttributes 에서 정의되는데 속성만 추가하려면 application.properties 에서 server.error 옵션들을 수정하던지 DefaultErrorAttributes 를 상속하여 커스텀 할 수도 있다.

 

# message 항목 보이기
server.error.include-message=always

 

@Component
public class CustomErrorAttributes extends DefaultErrorAttributes {

    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
        Map<String, Object> result = super.getErrorAttributes(webRequest, options);
        result.put("description", "abcdefg");
        return result;
    }
}

 

 

3. AbstractErrorController 상속하여 재정의

 

basicErrorController 처럼 ErrorController 인터페이스를 구현한 AbstractErrorController 를 상속하여 에러 응답을 재정의할 수 있다.

 

@RestController
@RequestMapping("${server.error.path:${error.path:/error}}")
public class CustomErrorController extends AbstractErrorController {

    public CustomErrorController(ErrorAttributes errorAttributes) {
        super(errorAttributes);
    }

    @RequestMapping
    public ResponseEntity<ErrorMessageEntity> customError(HttpServletRequest request) {
        HttpStatus httpStatus = getStatus(request);

        CustomResponseEntity customResponseEntity = new CustomResponseEntity();
        customResponseEntity.setCode(httpStatus.value());
        customResponseEntity.setMessgae(httpStatus.getReasonPhrase());
        customResponseEntity.setResult(null);

        return new ResponseEntity<>(customResponseEntity, httpStatus);
    }
}

 

@Entity
public class CustomResponseEntity {
    private Integer code;
    private String messgae;
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private String result;
    ...
}

 

기본 에러 경로인 /error (properties 파일: server.error.path) 는 basicErrorController 에서 매핑을 시도하므로, ErrorController 인터페이스를 구현하지 않고 /error 컨트롤러를 사용한다면 런타임 에러가 발생한다.

 

Caused by: java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'basicErrorController' method

 

 

4. ResponseStatusException 사용

 

위와 같이 AbstractErrorController 를 상속하면 모든 HTTP 상태 코드에 대한 응답을 커스텀 할 수 있다. 여기에 Spring 5+ 를 사용 중이라면 RuntimeException 을 상속하는 ResponseStatusException 를 이용해 어디에서든 원하는 에러를 발생시킬 수 있다.

 

throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid path");

 

특정 상황에 특정 에러 코드와 메시지로 응답하고 싶었는데 2번째 파라미터를 응답 엔티티에 넣는 것이 쉽지 않았다.

 

 

5. Custom Exception 생성

 

ResponseStatusException 을 대신하여 메시지도 응답할 수 있도록 CustomException 을 생성한다.

 

@Component
public class CustomException extends RuntimeException {

    private ErrorCode errorCode;

    public CustomException(ErrorCode errorCode) {
        this.errorCode = errorCode;
    }

    public ErrorCode getErrorCode() {
        return this.errorCode;
    }
}

 

에러 메시지를 enum 으로 정리한다.

 

public enum ErrorCode {
    
    EXPIRED_TOKEN(HttpStatus.UNAUTHORIZED, "Expired Token"),
    INVALID_TOKEN(HttpStatus.UNAUTHORIZED, "Invalid Token"),
    SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "Internal server error"),
    ...
    ;

    private final HttpStatus status;
    private final String message;

    ErrorCode(HttpStatus status, String message) {
        this.status = status;
        this.message = message;
    }

    public HttpStatus getStatus() {
        return this.status;
    }

    public String getMessage() {
        return this.message;
    }
}

 

컨트롤러 전역에서 에러를 핸들링할 수 있도록 @ControllerAdvice, @ExceptionHandler 를 작성한다.

 

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(CustomException.class)
    public ResponseEntity<CustomResponseEntity> myCustomException(CustomException ex) {
        CustomResponseEntity customResponseEntity = new CustomResponseEntity();

        ErrorCode errorCode = ex.getErrorCode();
        customResponseEntity.setCode = errorCode.getStatus().value();
        customResponseEntity.setMessage = errorCode.getMessage();

        return new ResponseEntity<>(customResponseEntity, errorCode.getStatus());
    }
}

 

특정 코드에 에러 발생시키기.

 

throw new CustomException(EXPIRED_TOKEN);

// output
{
    "code": 401,
    "message": "Expired Token"
}

 

 

6. 404 error 핸들러 추가

 

여기까지 하면 404 에러 발생시 에러 핸들러를 찾을 수 없다는 500 에러가 발생하게 되는데, dispatcher servlet 에서 요청을 처리할 수 없는 핸들러가 생긴다면 NoHandlerFoundException 예외를 발생시키도록 아래와 같이 수정한다.

 

# application.yaml
spring:
  mvc:
    throw-exception-if-no-handler-found: true
  web:
    resources:
      add-mappings: false

 

위 5번 GlobalExceptionHandler 에 아래 NoHandlerFoundException 추가하여 NoHandlerFoundException 예외를 처리한다.

 

@ExceptionHandler(NoHandlerFoundException.class)
public ResponseEntity<DefaultMessageEntity> handle404(NoHandlerFoundException ex) {
    CustomResponseEntity customResponseEntity = new CustomResponseEntity();
    customResponseEntity.setCode = HttpStatus.NOT_FOUND.value();
    customResponseEntity.setMessage = HttpStatus.NOT_FOUND.getReasonPhrase()

    return new ResponseEntity<>(customResponseEntity, HttpStatus.OK);
}

 

 

 

CustomException(EXPIRED_TOKEN) 이라는 에러를 발생시키면, @ExceptionHandler 에서 해당 예외를 처리하는 예제이다. CustomException 을 제외한 예외들은 3번에서 작성한 CustomErrorController 에 의해 처리될 것이다. 3번 5번 6번 조합!

 

 


WRITTEN BY
손가락귀신
정신 못차리면, 벌 받는다.

,

finalizers

Daily/Prog 2021. 12. 12. 03:17

EKS 에서 ingress 와 loadbalancer 를 생성했는데 pending 상태라 살펴보니 자격증명 실패 에러가 발생했다.

 

$ kubectl describe ingress my-ingress
Warning FailedBuildModel  32m (x9 over 47m)  ingress  (combined from similar events): Failed build model due to WebIdentityErr: failed to retrieve credentials
caused by: InvalidIdentityToken: Incorrect token audience
status code: 400, request id: 4599a6da-7a29-4d82-baf7-d546e7811234

 

확인하고 삭제하려는데 삭제가 안된다.ㅋ 강제 삭제(--force --grace-period=0)도 안된다; 시간이 한참 지나도 프롬프트가 멈춰버림.

 

$ kubectl describe svc my-nlb
...
Normal   DeletedLoadBalancer  40m  service-controller  Deleted load balancer
Warning  FailedDeployModel    38m  service             Failed deploy model due to WebIdentityErr: failed to retrieve credentials
Warning  ClusterIPNotAllocated  75s (x5 over 37m)  ipallocator-repair-controller    Cluster IP [IPv4]:172.20.23.140 is not allocated; repairing
Warning  PortNotAllocated       75s (x5 over 37m)  portallocator-repair-controller  Port 32083 is not allocated; repairing

 

권한은 없는데 복구 의지가 강해서 그런건지, 안죽고 계속 살아나려고 발버둥 치는 느낌. 다른 서비스들과 결합이 되어 있는건지... 클러스터를 거의 초기화 수준으로 다른 모든 리소스를 다 지웠는데도 삭제가 안되는 생명줄 긴 로드 밸런서들. 구글님 덕에 겨우 찾아 삭제했다.

 

$ kubectl patch service/<your_service> --type json --patch='[ { "op": "remove", "path": "/metadata/finalizers" } ]'
$ kubectl patch ingress <your_ingress> -n <your_ns> -p '{"metadata":{"finalizers":[]}}' --type=merge

 

finalizers 는 리소스를 완전히 삭제하기 전에 특정 조건이 충족될 때까지 대기하게 한다. 삭제가 완료되면 대상에서 관련 finalizers 를 삭제하는데, 위처럼 metadata.finalizers 필드를 비워주면 Kubernetes 는 삭제가 완료된 것으로 인식하게 된다.

 


WRITTEN BY
손가락귀신
정신 못차리면, 벌 받는다.

,

Tomcat 은 훌륭한 WAS 이다. 그대로 갖다 쓰면 되는 것을 이짓저짓 해가면서 에러를 발생시킨다. 오늘도 어김없이 뻘짓을 하다가 에러를 발생시킨다. Tomcat7 과 Tomcat8 을 동시에 올리는 과정에서 에러가 발생했다. 각각 그대로 썼다면 문제가 없었겠지만 멀티 인스턴스를 생성하는 과정에서 Tomcat7 기반에다가 Tomcat8 설정을 그대로 가져왔더니 에러가 발생했다. 왜 이런 짓을 했는지는 비밀이다.ㅋㅋ

 

28-Jun-2021 14:01:19.636 경고 [main] org.apache.catalina.startup.ClassLoaderFactory.validateFile Problem with directory [/app/tomcat7-jdk1.6/bin/"/app/instances/instance6/lib"], exists: [false], isDirectory: [false], canRead: [false]
28-Jun-2021 14:01:19.637 경고 [main] org.apache.catalina.startup.ClassLoaderFactory.validateFile Problem with directory [/app/tomcat7-jdk1.6/bin/"/app/instances/instance6/lib/*.jar"], exists: [false], isDirectory: [false], canRead: [false]
28-Jun-2021 14:01:19.637 경고 [main] org.apache.catalina.startup.ClassLoaderFactory.validateFile Problem with directory [/app/tomcat7-jdk1.6/bin/"/app/tomcat7-jdk1.6/lib"], exists: [false], isDirectory: [false], canRead: [false]
28-Jun-2021 14:01:19.638 경고 [main] org.apache.catalina.startup.ClassLoaderFactory.validateFile Problem with directory [/app/tomcat7-jdk1.6/bin/"/app/tomcat7-jdk1.6/lib/*.jar"], exists: [false], isDirectory: [false], canRead: [false]

 

음... 한글 로그가 참 눈에 거슬린다. 결론부터 얘기하자면 설정에 따옴표(") 가 붙은게 문제이다. tomcat8 에는 로더 간에 따옴표(")로 구분을 하였고, tomcat7 에는 따옴표가 없는데... 그 때문이다. 

 

(Tomcat8, conf/catalina.properties)
common.loader="${catalina.base}/lib","${catalina.base}/lib/*.jar","${catalina.home}/lib","${catalina.home}/lib/*.jar"

(Tomcat7, conf/catalina.properties)
common.loader=${catalina.base}/lib,${catalina.base}/lib/*.jar,${catalina.home}/lib,${catalina.home}/lib/*.jar

 

필요에 맞게 따옴표(") 를 넣거나 빼면 된다. 

 

기본 그대로 잘 쓰면 에러 안난다.ㅋ


WRITTEN BY
손가락귀신
정신 못차리면, 벌 받는다.

,
import pandas as pd
print(pd.__version__)
cs


Traceback (most recent call last):

  File "~\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3343, in run_code

    exec(code_obj, self.user_global_ns, self.user_ns)

  File "<ipython-input-2-22947d009327>", line 1, in <module>

    runfile('D:/Project_CTLab/Hong_Test2/pandas.py', wdir='D:/Project_CTLab/Hong_Test2')

  File "C:\Program Files\JetBrains\PyCharm 2020.2.3\plugins\python\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile

    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script

  File "C:\Program Files\JetBrains\PyCharm 2020.2.3\plugins\python\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile

    exec(compile(contents+"\n", file, 'exec'), glob, loc)

  File "D:/Project_CTLab/Hong_Test2/pandas.py", line 1, in <module>

    import pandas as pd

  File "C:\Program Files\JetBrains\PyCharm 2020.2.3\plugins\python\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import

    module = self._system_import(name, *args, **kwargs)

  File "D:\Project_CTLab\Hong_Test2\pandas.py", line 3, in <module>

    print(pd.__version__)

AttributeError: partially initialized module 'pandas' has no attribute '__version__' (most likely due to a circular import)


pandas 모듈 불러오면서 파일명을 pandas.py 로 저장했더니...ㅋㅋ







WRITTEN BY
손가락귀신
정신 못차리면, 벌 받는다.

,

간만에 재미진 일.


간만에 사이트 운영팀에서 오류 문의가 속출했다. 등록이 안된다느니, 상세 페이지가 빈화면으로 나온다느니... 훗~ 걱정마라. 언제나 처럼 이 오빠가 해결해 줄테니.


우선 이 님들의 증상이 나에게도 동일한지 확인하였다. 특정 페이지들이 서버 500 에러도 있었지만 status 200 인데 빈화면이 나오는 기괴한 장면이 보여졌다. 동일한 소스의 개발 서버에는 정상적으로 작동하고 있었다. 실서버 로그를 확인해보니, 어제 아무개팀에서 인증서를 갱신했다.(내가 하던걸 왠일로...) 근데 로그를 뒤져보니 그 시간 이후로 오류가 속출했다. 잡았다, 요놈!! 공통적으로 주로 나온 오류들이다. 


INFO [main] org.apache.coyote.AbstractProtocol.destroy Destroying ProtocolHandler ["https-jsse-nio-8443"]

java.util.logging.ErrorManager: 4

java.io.FileNotFoundException: /usr/share/tomcat8/logs/catalina.2020-01-08.log (Permission denied)

        at java.io.FileOutputStream.open0(Native Method)

...


INFO [main] org.apache.catalina.core.StandardService.stopInternal Stopping service [Catalina]

[localhost-startStop-2] ERROR o.a.c.s.StandardManager - Exception unloading sessions to persistent storage

java.io.FileNotFoundException: /usr/share/tomcat8/work/Catalina/localhost/ROOT/SESSIONS.ser (Permission denied)

        at java.io.FileOutputStream.open0(Native Method)

...


SEVERE [https-jsse-nio-8443-exec-6] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception

 org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadBase$IOFileUploadException: Processing of multipart/form-data request failed. /var/cache/tomcat8/work/Catalina/localhost/ROOT/upload_46c524e4_8548_4273_9717_ff2e98ca4a2d_00000000.tmp (Permission denied)

        at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.parseRequest (StandardMultipartHttpServletRequest.java:112)

...


그리고 status 200 이지만 빈화면 나오면서 발생한 로그...


[https-jsse-nio-8443-exec-9] ERROR o.s.b.w.s.ErrorPageFilter - Cannot forward to error page for request [/manage/admin/9] as the response has already been committed. As a result, the response may have the wrong status code. If your application is running on WebSphere Application Server you may be able to resolve this problem by setting com.ibm.ws.webcontainer.invokeFlushAfterService to false


조금 당황스러웠다. 평소에 보던 오류도 아니고... 한가지 힌트는 Permission denied 하난데. 히스토리를 보니 인증서 갱신하고 몇번 톰캣 재부팅을 하는 과정에서 사용자 권한이 좀 꼬인것 같았다. 문제되는 파일들의 소유자가 모두 ROOT 로 실행되어 있던것이 문제. 후... 인증서 갱신하고 톰캣 재부팅만 하면 되는건데 뭐 때문에 ROOT 로 톰캣을 실행시켰을까 ㅡ.ㅡ 톰캣 재부팅으로도 문제는 해결되지 않았다. 이 파일들을 다 일일히 어떻게 찾아서 지우나 고민하던 중 빛과 같은 한 줄기 로그.


[localhost-startStop-1] ERROR o.a.j.EmbeddedServletOptions - The scratchDir you specified: [/usr/share/tomcat8/work/Catalina/localhost/ROOT] is unusable.



캐쉬 디렉토리 같은데 /usr/share/tomcat8/work/Catalina/localhost/ROOT 이 디렉토리를 삭제하니 문제가 해결됐다.

오예~


WRITTEN BY
손가락귀신
정신 못차리면, 벌 받는다.

,