タイプスクリプトとcatchセクションのエラー処理
9198 ワード
JavaScriptは任意の値にエラーを投げ出すことができます.
他の言語のように、目的のエラータイプだけをキャプチャすることはできません.
catchセクション内部でエラータイプによって異なる処理を行う場合は、分岐処理が必要です
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
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
}
Referenceshttps://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
Reference
この問題について(タイプスクリプトとcatchセクションのエラー処理), 我々は、より多くの情報をここで見つけました https://velog.io/@shroad1802/타입스크립트와-catch절-에러-처리テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol