Middleware like plug

My understanding (albeit potentially flawed) is that there are three methods for handling errors, and two places for defining the error response in Phoenix:

  1. Return an :error tuple in the controller and use the fallback controller, as @D4no0 mentioned. Unfortunately, this is not helpful for you, as you’re dealing with a raised Ecto.NoResultsError.
  2. Handle the exception one level up in the router using Plug.ErrorHander, as @tfwright mentioned. However, I believe that this is more designed for handling side effects, as the error is reraised to be handled by point 3 below.
  3. Use the error view. Plug wraps up all exceptions that occur during the request/response, and these are caught by Phoenix in the Endpoint:magic_wand:, which then renders a special error view:magic_wand:. You can customise this to return the JSON response you like - I think this is the best solution. See the documentation.