Skip to content
Permalink
Browse files

## Handling Errors

Our Phoenix-based web application is now successfully serving content from the `/` route. If we navigate to `http://localhost:4000/`, we’ll be greeted by our friendly `HomeController`:

![Home route
image](https://s3-us-west-1.amazonaws.com/www.east5th.co/img/minimum-viable-phoenix/minimal-1.png)

But behind the scenes, we’re having issues. Our browser automatically requests the `/facicon.ico` asset from our server, and having no idea how to respond to a request for an asset that doesn’t exist, Phoenix kills the request process and automatically returns a `500` HTTP status code.

![500
image](https://s3-us-west-1.amazonaws.com/www.east5th.co/img/minimum-viable-phoenix/minimal-2.png)

We need a way of handing requests for missing content.

Thankfully, the stack trace Phoenix gave us when it killed the request process gives us a hint for how to do this:

	Request: GET /favicon.ico
	  ** (exit) an exception was raised:
	    ** (UndefinedFunctionError) function MinimalWeb.ErrorView.render/2 is undefined (module MinimalWeb.ErrorView is not available)
	        MinimalWeb.ErrorView.render("404.html", %{conn: ...

Phoenix is attempting to call `MinimalWeb.ErrorView.render/2` with `"404.html"` as the first argument and our request’s `conn` as the second, and is finding that the module and function don’t exist.

Let’s fix that:

	defmodule MinimalWeb.ErrorView do
	  def render("404.html", _assigns) do
	    "Not Found"
	  end
	end

Our `render/2` function is a view, not a controller, so we just have to return the content we want to render in our response, not the `conn` itself. That said, the distinctions between [views](https://hexdocs.pm/phoenix/Phoenix.View.html) and [controllers](https://hexdocs.pm/phoenix/Phoenix.Controller.html) may be outside the scope of building a “minimum viable Phoenix application,” so we’ll skim over that for now.

Be sure to read move about [the `ErrorView` module](https://hexdocs.pm/phoenix/views.html#the-errorview), and how it incorporates into our application’s endpoint. Also note that the module called to render errors is customizable through [the `:render_errors` configuration option](https://hexdocs.pm/phoenix/Phoenix.Endpoint.html#module-compile-time-configuration).
  • Loading branch information...
pcorey committed May 8, 2019
1 parent 5350b88 commit 3dbd3c3b59281589f500c84c320db874959cb3fe
Showing with 5 additions and 0 deletions.
  1. +5 −0 lib/minimal_web/views/error_view.ex
@@ -0,0 +1,5 @@
defmodule MinimalWeb.ErrorView do
def render("404.html", _assigns) do
"Not Found"
end
end

0 comments on commit 3dbd3c3

Please sign in to comment.
You can’t perform that action at this time.