Last active
September 15, 2024 10:02
-
-
Save fsubal/193e4ce34def8b5bf208675ee2ec4198 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* `try ... catch`で`any`や`unknown`が来たときに、こいつに渡すとすべてをいい感じにしてくれる。 | |
* | |
* ただし、あくまで単一のエラーに対して使う想定。 | |
* 複数のエラーをまとめる用途には、標準の`AggregateError`を使うこと。 | |
* | |
* @see https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/AggregateError | |
* | |
* @example | |
* ```ts | |
* try { | |
* // ... | |
* } catch (e: unknown) { | |
* throw new AppError(e) | |
* } | |
* ``` | |
*/ | |
export class AppError<T> extends Error { | |
readonly originalError: T | |
constructor(e: T, option?: { cause?: unknown }) { | |
if (typeof e === 'string') { | |
super(e, option) | |
} else if (e instanceof Error) { | |
super(e.message, { cause: e.cause, ...option }) | |
} else { | |
super(`Unknown Error: ${JSON.stringify(e)}`, { cause: e, ...option }) | |
} | |
this.originalError = e | |
} | |
} | |
try { | |
// ... | |
} catch (e) { | |
const error = new AppError(e) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyError extends Error {} | |
try { | |
// | |
} catch (e: unknown) { | |
throwUnless(e, TypeError) | |
e.message | |
} | |
function throwUnless<T extends Error>( | |
value: unknown, | |
is: new (...args: any[]) => T | |
): asserts value is T { | |
if (!(value instanceof is)) { | |
throw value | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment