1

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" })
     }
  }
}

2 Answers 2

2

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...

Sign up to request clarification or add additional context in comments.

17 Comments

Glad I could help
Your right... And the documentation is not really clear on this point
Hi ernest... I have a question... when I start my hapi server then doesn't show any logs... Do you have any idea about it? If you know the answer then I will raise a question for it
Yes I have the answer. Check the "creating a server" section here hapijs.com/tutorials. For hapi version below 17, you should put a console.log in the server.start callback
Do you mean this options: { prettyPrint: false, logEvents: ['response'] }??
|
1

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.

3 Comments

Thank you Sparw... is there any better way to do it?
I'm not sure there is a better way to do that properly.. :/
your answer helps me to change the message and Ernest's answer helps me to return that messsage... So thanks it works...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.