Adding an Error Handler for 404s for JSON

Phoenix, as of version 1.3, included the ability to define fallback controllers or plugs to handle scenarios where a conn is not returned back out. We can harness this to write custom error handling code for our API to catch these scenarios!

We'll start off by creating a new controller called ErrorController for our API. Create lib/vocial_web/controllers/api/error_controller.ex:

defmodule VocialWeb.Api.ErrorController do  use VocialWeb, :controllerend

Next, for a handler controller, you need to define a call function that will attempt to look for a conn as the first argument and pattern match against the second argument. We'll just implement a simple 404 handler for purposes of this example:

def call(conn, ...

Get Phoenix Web Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.