저장을 습관화

NestJS의 라이프 사이클 본문

공부/node.js

NestJS의 라이프 사이클

ctrs 2023. 12. 20. 12:39

메모..

nestJS에 요청이 들어올때 이에 반응하여 동작하는 기능들의 선후관계이다.

먼저 동작하는 부분에 에러가 발생했을 경우 후에 동작하는 부분까지 요청이 가지 않으니,

이 순서를 기억해둔다면 개발 중 문제가 생겼을때 원인을 찾는데에 도움이 될 것이다.

 

1. 요청 수신(Request)

 

2. 미들웨어

2-1. 전역 미들웨어

2-2. 모듈 미들웨어

 

3. 가드

3-1. 전역 가드

3-2. 컨트롤러 가드

3-3. 루트(경로) 가드

 

4. 인터셉터(컨트롤러 수행 전)

4-1. 전역 인터셉터

4-2. 컨트롤러 인터셉터

4-3. 루트 인터셉터

 

5. 파이프

5-1. 전역 파이프

5-2. 컨트롤러 파이프

5-3. 루트 파이프

5-4. 루트 매개변수 파이프

 

6. 컨트롤러

 

7. 서비스 (존재하지 않는 경우도 있음)

 

8. 인터셉터 (컨트롤러 수행 후)

8-1. 루트 인터셉터

8-2. 컨트롤러 인터셉터

8-3. 전역 인터셉터

 

9. 예외 필터(Exception filter, 예외 처리 담당)

9-1. 루트

9-2. 컨트롤러

9-3. 전역

 

10. 응답(Response)

 

원본

 

위와 같이 순서대로 적으니 익셉션 필터가 모든 과정이 끝난 후 동작한다는 느낌이 드는데 그렇지 않다.

아래와 같이 그림으로 봤을때, 익셉션  필터는 가드, 인터셉터, 파이프, 컨트롤러를 포함하고 있다.

출처: https://slides.com/yariv-gilad/nest-js-request-lifecycle#/1

 

가드, 인터셉터, 파이프, 컨트롤러(및 서비스) 과정을 처리하는 도중에 에러가 발생하였고,

이 에러에 대한 처리를 익셉션 필터가 담당하고 있다면 nestJS는 동작을 멈추고 

익셉션 필터에 지정된 내용에 따라 예외 처리를 진행한다.

 

다시 말해 여러 테스트를 거쳐 에러가 발생했거나, 발생할 것 같은 부분에는 에러 처리를 걸어주는 것이 좋겠다.

 

사용할 수 있는 필터 목록은 아래 공식 문서를 참조하자

https://docs.nestjs.com/exception-filters

 

Documentation | NestJS - A progressive Node.js framework

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Rea

docs.nestjs.com

 

 

[참조]

https://docs.nestjs.com/faq/request-lifecycle

 

Documentation | NestJS - A progressive Node.js framework

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Rea

docs.nestjs.com

https://slides.com/yariv-gilad/nest-js-request-lifecycle

 

Nest.js Request lifecycle

A presentation created with Slides.

slides.com