Ashh
Ashh

Reputation: 46451

How to handle hapi validation errors?

I have following route code for hapi...


const routeConfig = {
  method: 'POST',
  path: '/user',
  config: {
    validate: {
      payload: {
        firstName: Joi.string().required(),
      }
    },
    handler
  }
}

So when I don't pass the firstName it throws error like this

{
    "statusCode": 400,
    "error": "Bad Request",
    "message": "child \"firstName\" fails because [\"firstName\" is required]",
    "validation": {
        "source": "payload",
        "keys": [
            "firstName"
        ]
    }
}

Now, I need to handle the above error in catch

const handler = async(request, reply) => {
  try {
    const payload = request.payload
    const createUser = await User.create(payload)
    let token = Helpers.createJwt(createUser) 
    reply({ success: true, message: 'User created successFully', token })
  } catch(err) {
     // need to do something here to handle the error like
     if (err) {
       reply ({ error: "firstName is required", message: "Signup unsuccessfull" })
     }
  }
}

Upvotes: 1

Views: 1663

Answers (2)

Ernest Jones
Ernest Jones

Reputation: 584

There is a much better solution:

config: {
        validate: {
            payload: {
                firstName: Joi.string().required(),
            },
            failAction(request, reply, source, error) {
              reply({
                error: 'badRequest',
              }).code(400);
            },
        },
    },

If the Joi validation fails, it will trigger the failAction and you will be able to handle the error (sending it to log service and/or return a specific message).

It's a bit hidden in the doc but here is the relevant part

I must confess, I did'nt tried it with hapi 17...

Upvotes: 2

Sparw
Sparw

Reputation: 2743

Maybe you should try with something like this ?

const routeConfig = {
  method: 'POST',
  path: '/user',
  config: {
    validate: {
      payload: {
        firstName: Joi.string().required().error(new Error('firstName is required')),
      }
    },
    handler
  }
}

Take a look on this page here

Hope it helps.

Upvotes: 1

Related Questions