Phoenix - returning custom 500 (Internal Server Error). How to?

I need to return a custom error message (json) for Internal Server Error.
The message is needed for explaining some error causes such as: corrupt file, internal path not found, bad json, python script execution error etc.
The 500 error would be raised in certain places in my Phoenix web API code when such upstream errors/exceptions occurs.

In the official doc is not clear how exactly to do this.

Thanks for help!

|> put_status(500)
|> json(%{error: "Custom error message"})

Will this work for you?

Thanks but not really… different context, cannot use conn there
I need something to “raise”:
raise MyApp.MyCustomError {<code>, <msg>}
more exactly:
raise MyApp.MyCustomError {:500, "Script did not execute successfully"}
I think you got the idea.

have you tried to just return a map? I got the idea from here

Review the Custom Exceptions section of that same guide.

You will need a defimpl Plug.Exception if you want your exception to be rendered as an HTTP response through Plug.

If you want to render your custom error in production, you will also need to add a pattern match to the render/2 function on your ErrorView. To ensure this is working correctly, you may want to set debug_errors: false on your Endpoint config in
dev.exs. :slight_smile:

Edits: typos


Thanks, I eventually managed to do it with defimpl.
I’m writing here the solution, it might help others with similar issues:
In the myapp_web.ex:

defmodule Myapp.Customerror do
  defexception [:message]

defimpl Plug.Exception, for: Myapp.Customerror do
  def status(_exception), do: 500


  def render("500.json", %{conn: conn}) do
    %{error: conn.assigns.reason.message}

.Finally, in my code:

raise Myapp.Customerror, "My custom message"