상세 컨텐츠

본문 제목

[node] Error.captureStackTrace() (feat. 문제 해결력을 증진시키는 flow)

TIL (Today I Learned)

by NayC 2022. 2. 7. 10:22

본문

728x90

 

 

상황

module.exports = function TistoryError(message, status, sentry = false, extras, rspCode) {
  Error.captureStackTrace(this, this.constructor);
  this.name = this.constructor.name;
  this.message = message;
}

require('util').inherits(module.exports, Error);

 

이런 코드가 있었다고 했을 때, captureStackTrace 함수를 처음 마주쳐서 무슨 기능을 하는건지 알 수 없었다. 

 

잘못된 방향

captureStackTrace를 무작정 구글링

 

올바른 방향

해당 코드에서 레이어를 더 들어갈 수 있다면 계속 들어가주기

-> "아 이건 node 쪽 함수구나" 하고 node의 doc에서 살핀다. 

 

* 실제 있었던 일 * 
 
맨 처음에 captureStackTrace를 구글링한 결과 MDN에서 deprecated된 함수를 것을 봤다. 그래서 안쓰이는건가? 싶었는데, 다시 보니 이건 javascript쪽 함수였다. 

node모듈 내에 있다는 것을 확인하고선 node document에서 확인해보니 여기서는 deprecated가 아닐 뿐더러 많이 쓰이는거였다! 

 

node document를 볼 때도, 버전 별로 내용이 다를 수도 있기 때문에 '해당' 버전에 맞는 document로 봐주기

- https://nodejs.org/ko/docs/

 

카테고리 선정

- 이건 Error 부분이다! 

 

함수 검색

- 이렇게 '바로'^_^ 있음을 확인할 수 있었다.

 

그리고 이해! 

- 이 document를 봐도 이해를 못하겠다? 

  그럼 또 다른 걸 검색하지 말고, 여기서 결판내기. 글 속에 다른 개념들을 몰라서 이해가 안 갈 가능성이 크니, 되려 그 개념들을 검색해서 doc을 이해할 것

 

 


Error.captureStackTrace(targetObject[, constructorOpt])#

Creates a .stack property on targetObject, which when accessed returns a string representing the location in the code at which Error.captureStackTrace() was called.

const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack;  // Similar to `new Error().stack`

The first line of the trace will be prefixed with ${myObject.name}: ${myObject.message}.

The optional constructorOpt argument accepts a function. If given, all frames above constructorOpt, including constructorOpt, will be omitted from the generated stack trace.

The constructorOpt argument is useful for hiding implementation details of error generation from the user. For instance:

function MyError() {
  Error.captureStackTrace(this, MyError);
}

// Without passing MyError to captureStackTrace, the MyError
// frame would show up in the .stack property. By passing
// the constructor, we omit that frame, and retain all frames below it.
new MyError().stack;

 

직접 해보는게 가장 좋지

 

captureStackTrace.js

const TistoryError = require('./captureStackTrace2');

const a = 3;

try{
    if (a != 2){
        throw new TistoryError("오류입니당", 404);
    }
}catch (err) {
    console.log(err);
}

 

captureStackTrace2.js

module.exports = function TistoryError(message, status, sentry = false, extras, rspCode) {
    Error.captureStackTrace(this, this.constructor);
    this.name = this.constructor.name;
    this.message = message;
    this.status = status;
    this.sentry = sentry;
    this.extras = extras;
    this.rspCode = rspCode;
}

require('util').inherits(module.exports, Error);

 

나는 결과로 message에도 "오류입니당"이 잘 나오는걸 예측했는데,  at Object.<anonymous> 라는 오류가 뜬다. 

 

// 

 

근데 captureStackTrace.js 에서 err.message를 하면 또 잘 출력이 된다. 

}catch (err) {
    console.log(err.message);
}

왜 err 객체는 올바르게 출력이 되지 않을까? 

그리고 err만 출력했을 때 다른 부분은 다 정상 출력 되는데, 왜 message만 출력되지 않을까? 

 

 

놀라운 발견

captureStackTrace2.js에서 captureStackTrace를 주석처리하고 돌려보니, console.log(err)가 정상 출력된다.

module.exports = function TistoryError(message, status, sentry = false, extras, rspCode) {
    //Error.captureStackTrace(this, this.constructor);
    this.name = this.constructor.name;
    this.message = message;
    this.status = status;
    this.sentry = sentry;
    this.extras = extras;
    this.rspCode = rspCode;
}

require('util').inherits(module.exports, Error);

 

 

잠깐만. 

이전에가 오류가 아니라, 뭔가를 더 출력했다고 볼 수도 있겠구나. 

-> Error.captureStackTrace는 어느 부분에서 에러가 난 것인지까지 그 히스토리를 알려주는 함수였다. 

very important one is the Error stack trace. You can access it through the `stack` property. The error stack will give you a history (call stack) of what files were ‘responsible’ of causing that Error. The stack also includes the message at the top and is then followed by the actual stack starting with the most recent / isolated point of the error and going down to the most outward ‘responsible’ file:


출처 : https://levelup.gitconnected.com/the-definite-guide-to-handling-errors-gracefully-in-javascript-58424d9c60e6

 

 

결과

진짜 더 잘 알 수 있었다. 

직접 해보기가 최고다. 

 

 

728x90
반응형

'TIL (Today I Learned)' 카테고리의 다른 글

환경 설정) test run (feat. debug)  (0) 2022.02.09
호스팅형 vs 설치형 (feat. Cloud hosting vs Self hosting)  (0) 2022.02.07
jwt  (0) 2022.01.27
node - middleware) express-validator  (0) 2022.01.26
[js] 생성자  (0) 2022.01.24

관련글 더보기