es-http-error
HttpError class for browsers (without Node.js dependencies)
Installation
$ npm install es-http-error
Usage
throw new HttpError(404)
throw new HttpError(401, 'Unauthorized')
Supported http status codes are here.
Example
import HttpError from 'es-http-error'
main()
async function main (id) {
try {
const res = await fetch('/api/something/great')
if (!res.ok) throw new HttpError(res.status)
const render(view(await res.json()), document.body)
} catch (e) {
if (e instanceof HttpError) {
if (e.code === 401) logout()
if (e.code === 404) notFound()
} else throw e
}
}
Motivation
There're some prior arts like below, but I couldn't find the one for browsers. So I made it.
...etc.
License
MIT