JavaScript
js/throw-error-objects
Throw and reject with Error objects (or subclasses), never with strings or plain objects.
drobnastatycznefe-javascript
Dlaczego
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.
Poprawka
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.
Przykłady
// 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'))Źródła
Fakty
- Identyfikator
js/throw-error-objects- Waga
- drobna
- Sprawdzanie
- statyczne sprawdzane w kodzie źródłowym przez
audit - Dotyczy plików
jsxhtmlvuesvelteastro- Uczy jej skill
fe-javascriptJavaScript in the browser- Od wersji
- 0.1.0
Przeczytaj w terminalu
npx github:dawidolko/frontend-skills explain js/throw-error-objects