es-http-error
HttpError class for browsers (without Node.js dependencies)
Installation
$ npm install es-http-error
Usage
throw 404 // 'Not Found' as a default messagethrow 401 'Unauthorized' // Custom Error Messagethrow statusCodesnotFound; // Using with enums
Supported http status codes are here.
Example
{ try // retrieve some data from API server const res = await // check the response and throw an error if it's not ok if !resok throw resstatus // for example, render the view by lit-html const renderviewawait res.json document.body catch e if e instanceof HttpError if ecode === 401 // check the code simply by number if ecode === statusCodesnotFound // or via statusCodes else throw e }
i18n
try throw 404 catch e console // translated message "未検出"
Supported languages are listed here.
Serverside Usage (on Node.js)
This library also provides a CommonJS vesion complementally.
Note: there's no support for i18n for CommonJS version.
const HttpError = const statusCodes = HttpError throw statusCodesnotFound
Motivation
There're some prior arts like below, but I couldn't find the one for browsers. So I made it.
- boom
- http-errors
- http-error - So close! But it has dependency for
util
.
...etc.
License
MIT