タイプスクリプトとcatchセクションのエラー処理


JavaScriptは任意の値にエラーを投げ出すことができます.
throw 123
throw 'hello!'
throw new Error('Unexpected Error!')
したがって、タイプスクリプトでは、エラーはunknownタイプに設定される.
try {
	throwError();
} catch(e) {
	// e: unknown
}
どんなタイプのボールも投げられますが、間違った物体を投げることをお勧めします
他の言語のように、目的のエラータイプだけをキャプチャすることはできません.
catchセクション内部でエラータイプによって異なる処理を行う場合は、分岐処理が必要です
catch(e) {
	if (e instanceof TypeError) {
		// TypeError
	}
	else if (e instanceof SyntaxError) {
		// SyntaxError
	}
	else if (typeof e === 'string') {
		// string
	}
	else {
		// other
	}
}
通常、catchセクションはサービス開発時に多くのログを出力し、エラー・オブジェクトはメッセージ構成を出力し、エラー・オブジェクトでない場合は文字列に変更してログを出力します.
catch(e) {
	if (e instanceof Error) {
		logger.error(e.message)
	} else {
		logger.error(String(e))
	}
}
ここです。で提案されたエラー情報抽出方法も良い
type ErrorWithMessage = {
  message: string
}

function isErrorWithMessage(error: unknown): error is ErrorWithMessage {
  return (
    typeof error === 'object' &&
    error !== null &&
    'message' in error &&
    typeof (error as Record<string, unknown>).message === 'string'
  )
}

function toErrorWithMessage(maybeError: unknown): ErrorWithMessage {
  if (isErrorWithMessage(maybeError)) return maybeError

  try {
    return new Error(JSON.stringify(maybeError))
  } catch {
    // 순환 참조와 같이 JSON.stringify에서 에러가 발생하는 경우 처리
    return new Error(String(maybeError))
  }
}

function getErrorMessage(error: unknown) {
  return toErrorWithMessage(error).message
}
References
https://fettblog.eu/typescript-typing-catch-clauses/
https://kentcdodds.com/blog/get-a-catch-block-error-message-with-typescript
https://github.com/kentcdodds/kentcdodds.com/issues/206