arb / celebrate

A joi validation middleware for Express.
MIT License
1.33k stars 66 forks source link

Question about custom errors #172

Closed JonasFreireAlcantara closed 4 years ago

JonasFreireAlcantara commented 4 years ago

There exists some feature in celebrate to produce custom error (401, 402, 404, etc) with the same shape from the middleware errors() ?

I know the issue #131 talks about format() function, but I didn't find this function in the code.

arb commented 4 years ago

Do you want the exact same error response but just a different status code or do you want a completely different response shape entirely?

Also what version of celebrate are you using?

JonasFreireAlcantara commented 4 years ago

The same error response shape but to a different status code.

Example

For a key property validation in body request, the response is:

{
  "statusCode": 400,
  "error": "Bad Request",
  "message": "\"author\" is required",
  "validation": {
    "source": "body",
    "keys": [
      "author"
    ]
  }
}

An error response shape would be:

{
  "statusCode": 401,
  "error": "Unauthorized",
  "message": "Unauthorized to access the resource",
}

The error property would be automatically from the statusCode and message passed from the user at error creation:

next({
  "statusCode": 401,
  "message": "Unauthorized to access the resource",
});

Version of celebrate: 12.0.1

arb commented 4 years ago

As of right now, your best bet would be to write your own error handler and using isCelebrate to check for errors originating from celebrate middleware.

format() (which has been migrated to CelebrateError) is a way to create celebrate style errors in the event that you want to do some Joi validation in your handlers but still want to leverage any express error handlers you have built. I don't think that's what you're looking for if I understand your question correctly.

The built in errors handler was built to mimic hapi as closely as possible and doesn't currently have any configuration options.

JonasFreireAlcantara commented 4 years ago

Oh I got it, thank you for the explanation !

arb commented 4 years ago

I've opened #173 which should allow you to override the status code and message. Not sure if that would suit your needs since it sounds like you may want some logic controlling the exact status code though.