Replies: 3 comments 1 reply
-
Hmm, I believe best practice is to only throw Of course, the place where this comes in handy is when you don't have control of what's being thrown. Or maybe you prefer a defensive coding style (“always assume the worst”). Although, I'd say there is such a thing as being “too defensive” and the proposed function may be crossing that line. In most cases, it's best to fix/fork the upstream package, instead of catering your error handling logic to its unadvisable behavior, and I don't want Radashi to encourage that. |
Beta Was this translation helpful? Give feedback.
-
@aleclarson One option is to typecheck the error, this will mute Typescript function throwing() {
throw new Error('Just a error')
}
function test() {
try {
throwing()
} catch (error) {
if (error instanceof Error) {
console.log(error)
}
}
} The proposed function solves this problem in just one line of code without a type check. try {
runFragileOperation()
} catch (err) {
const error = ensureError(err)
console.log(error.message)
} I know the differences between the |
Beta Was this translation helpful? Give feedback.
-
OK, fair enough |
Beta Was this translation helpful? Give feedback.
-
As explained here, error handling in Typescript can be tedious because the catch returns
unknown
type.I've been using the
ensureError
function every since I read the article, it could be a usefull addition toradashi
.Beta Was this translation helpful? Give feedback.
All reactions