JavaScript
js/throw-error-objects
Throw and reject with Error objects (or subclasses), never with strings or plain objects.
minorstaticfe-javascript
Why
A thrown string has no stack trace, no name and no cause, so the error report says only "Uncaught Load failed" with no file or line. Code that catches it cannot tell it apart with instanceof, and error.message is undefined.
Fix
throw new Error('Load failed', { cause: err }), or a subclass (class HttpError extends Error) when callers need to tell errors apart. Reject promises with Error objects as well.
Examples
// bad
if (!res.ok) throw 'Load failed'
return Promise.reject({ code: 404 })
// good
if (!res.ok) throw new HttpError(res.status, 'Load failed')
return Promise.reject(new HttpError(404, 'Not found'))Sources
Facts
- Id
js/throw-error-objects- Severity
- minor
- Check
- static checked in the source by
audit - Applies to
jsxhtmlvuesvelteastro- Taught by the skill
fe-javascriptJavaScript in the browser- Since version
- 0.1.0
Read it in the terminal
npx github:dawidolko/frontend-skills explain js/throw-error-objects