hapi — How to Fix “handler method did not return a value, a promise, or throw an error”

The hapi v17 release comes with a paradigm shift from callbacks to async/await. This shift includes a learning curve for hapi developers, too. You’ll run into errors like handler method did not return a value, a promise, or throw an error.

What does this error mean and how to solve it?
Let’s make it clear in this tutorial.

hapi Series Overview

What’s Causing the Problem?

The error message means that you returned undefined or null from your route handler. Hapi v17 expects you to return either a value, a promise or an error. Otherwise, the framework wouldn’t know what response to send.

Let’s look at the following sample code. It represents a route handler that searches for a tutorial based on a given slug. After the search, you return the tutorial right away.

'use strict'

handler: async (request, h) => {  
  const slug = request.params.slug
  const tutorial = await Tutorial.findBySlug(slug)

  // tutorial might be undefined
  // hapi wouldn’t know what "undefined" represents: success, error, server error?
  return tutorial
}

If the findBySlug() method on the Tutorial class does not throw an error, the value for tutorial would result in undefined.

The Solution: Always Return

Make sure to always return values, promises or errors from route handlers. That’s the way hapi knows how to respond the request.

The refactored code from above can have an extra check to send an error if there is no tutorial available for the given slug.

'use strict'

handler: async (request, h) => {  
  const slug = request.params.slug
  const tutorial = await Tutorial.findBySlug(slug)

  // explicitly return from route handlers: values, promises or errors

  if (!tutorial) {
    throw Boom.notFound(`No tutorial available for slug »${slug}«`)
  }

  return tutorial
}

The code snippet above shows two different responses: 404 Not Found response if there is no tutorial with the given slug or 200 OK if the slug matches a tutorial.

Summary

Watch out that all route handlers return values, either an actual value, an error or promises. Add checks in your code and respond with errors to situations where no “success” response is applicable.

Explore the Library

Find interesting tutorials and solutions for your problems.