http-errors icon indicating copy to clipboard operation
http-errors copied to clipboard

httpError(N, error) is misleading if error is already an HTTP error

Open innermatrix opened this issue 2 years ago • 3 comments

I would expect

httpError(500, httpError(402)).statusCode

to be 500, but it's 402.

(The use case here is that I have a try/catch statement that turns all exceptions into HTTP 500s by default, and it's not working correctly when the original exception is already an httpError.)

innermatrix avatar May 22 '23 16:05 innermatrix

Mmm, yes, that is good point. Unfortunately it is the current behavior relied upon by existing uses (that a given error object will have it's status code preserved over the argument status code). This is regardless of the error being httpError or not. So the docs are not clear on this, but I also lile the idea of how you would like it to behave too, so I think we should support both somehow. I will think on the API for that 👍

dougwilson avatar May 22 '23 16:05 dougwilson

Currently createErrors has a very loose args interface.

I was surprised this issue was possible, because we will ignore any status passed in via the additional props bag. But because we are passing something which is instanceof Error, we will honor the status.

it doesn't matter what position we pass an error in, if it is detected in args we will set the status there.

So consider also:

const createErrors = require('http-errors')
const err = new Error()
err.statusCode = 411

const createdError = createErrors(
  createErrors(404),
  createErrors(414),
  { bag: 'foo', status: 500 },
  createErrors(400, createErrors(err)),
  { bag: 'foo', status: 429 },
  404
)

console.log(createdError.statusCode === 411) // true

The last instance of an Error wins. The properties bag uses the props but ignores status

jonchurch avatar Mar 10 '24 01:03 jonchurch

Well done

AIEINC avatar Mar 11 '25 15:03 AIEINC