typescript) try...catch문에서 error 객체의 type assertion

김명성·2022년 7월 18일
0

error 객체의 message를 사용하려 할 때 Object is type 'unknown'이라는 오류문구를 볼 수 있다.
try ...catch문에서의 error 객체는 unknown 또는 any타입으로만 정의할 수 있기 때문에 발생하는 에러다.

변수에 error 객체를 할당하고, assertion을 통해 타입을 지정해주면 쉽게 error를 정의할 수 있다.


error 발생

catch (err) {
      return {
        code: '',
        err: err.message // Object is of type 'unknown'
      };
  }

아래는 full code.
type assertion으로 error 객체의 message를 extract한다.

 try {
    result = await esbuild.build({
      // 번들링 진입점
      entryPoints: ['index.js'],
      bundle: true,
      write: false,
      // plugins - onLoad - contents에 들어가야 할 inputValue
      plugins: [unpkgPathPlugin(), fetchPlugin(rawCode)],
      define: {
        global: 'window',
      },
    });
    initialized = true;
    return {
      code: result.outputFiles[0].text,
      err: ''
    };
  } catch (err) {
    // assertion
    const typedError = err as Error
      return {
        code: '',
        err: typedError.message
      };
  }

또는 다음과 같이 사용할 수 있다

if(err instanceof Error){
      console.log('Problem occured. check this message =>', err.message)
    }

확실히 들어오는 프로퍼티가 있다면 interface extends를 사용해 확장할 수 있다.

interface ErrorMessage extends Error{
  code: string
}
...
  try{
    const result = await fs.readFile(fullpath, {encoding: 'utf-8'});
    res.status(200).send(JSON.parse(result));
  }catch(err){
    const typedError = err as ErrorMessage
    if(typedError.code){
      await fs.writeFile(fullpath,'[]')
    }
  }

0개의 댓글