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
jsx html vue svelte astro
Uczy jej skill
fe-javascript JavaScript in the browser
Od wersji
0.1.0

Plik reguły na GitHubie

Przeczytaj w terminalu

npx github:dawidolko/frontend-skills explain js/throw-error-objects