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')
throw new HttpError(statusCodes.notFound);
Supported http status codes are here.
Example
import HttpError, {statusCodes} 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 === statusCodes.notFound) notFound()
} else throw e
}
}
i18n
import HttpError, {statusCodes} from 'es-http-error/langs/ja'
try {
throw new HttpError(404)
} catch (e) {
console.log(e.message)
}
Supported languages are listed here.
Motivation
There're some prior arts like below, but I couldn't find the one for browsers. So I made it.
...etc.
License
MIT