Skip to content

Commit

Permalink
Use http-errors to set status code on errors
Browse files Browse the repository at this point in the history
  • Loading branch information
dougwilson committed Sep 8, 2017
1 parent 29a27f1 commit 7b9cb14
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 26 deletions.
1 change: 1 addition & 0 deletions HISTORY.md
Expand Up @@ -2,6 +2,7 @@ unreleased
==========

* Fix JSON strict violation error to match native parse error
* Use `http-errors` to set status code on errors
* deps: bytes@3.0.0
* deps: debug@2.6.8
* deps: depd@~1.1.1
Expand Down
7 changes: 4 additions & 3 deletions README.md
Expand Up @@ -273,9 +273,10 @@ encoding of the request. The parsing can be aborted by throwing an error.
## Errors

The middlewares provided by this module create errors depending on the error
condition during parsing. The errors will typically have a `status` property
that contains the suggested HTTP response code and a `body` property containing
the read body, if available.
condition during parsing. The errors will typically have a `status`/`statusCode`
property that contains the suggested HTTP response code, an `expose` property
to determine if the `message` property should be displayed to the client and a
`body` property containing the read body, if available.

The following are the common errors emitted, though any error can come through
for various reasons.
Expand Down
26 changes: 3 additions & 23 deletions lib/read.js
Expand Up @@ -75,9 +75,6 @@ function read (req, res, next, parse, debug, options) {
debug('read body')
getBody(stream, opts, function (err, body) {
if (err) {
// default to 400
setErrorStatus(err, 400)

// echo back charset
if (err.type === 'encoding.unsupported') {
err = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
Expand All @@ -88,7 +85,7 @@ function read (req, res, next, parse, debug, options) {
// read off entire request
stream.resume()
onFinished(req, function onfinished () {
next(err)
next(createError(400, err))
})
return
}
Expand All @@ -99,9 +96,7 @@ function read (req, res, next, parse, debug, options) {
debug('verify body')
verify(req, res, body, encoding)
} catch (err) {
// default to 403
setErrorStatus(err, 403)
next(err)
next(createError(403, err))
return
}
}
Expand All @@ -120,10 +115,7 @@ function read (req, res, next, parse, debug, options) {
? body
: str

// default to 400
setErrorStatus(err, 400)

next(err)
next(createError(400, err))
return
}

Expand Down Expand Up @@ -175,15 +167,3 @@ function contentstream (req, debug, inflate) {

return stream
}

/**
* Set a status on an error object, if one does not exist
* @private
*/

function setErrorStatus (error, status) {
if (!error.status && !error.statusCode) {
error.status = status
error.statusCode = status
}
}

0 comments on commit 7b9cb14

Please sign in to comment.