I am new to Elixir and started to learn getting my hands dirty it with.
I am trying to write a simple REST service in Elixir without Phoenix framework. I have an EndPoint as below.
defmodule MyEndPoint do
use Plug.Router
use Plug.Debugger
use Plug.ErrorHandler
alias Plug.Cowboy
require Logger
@content_type "text/json"
plug(Plug.Logger, log: :debug)
plug(:match)
# As we want our API to be JSON-compliant, we are implementing
# Plug.Parsers here. We will use it for parsing the request body
# because it handles application/json requests with :json_decoder.
plug(Plug.Parsers,
parsers: [:json],
pass: ["application/json"],
json_decoder: Jason
)
plug(:dispatch)
forward("/payments", to: PaymentRouter)
end
It forwards requests just fine as far as a valid json request body is sent in the POST request.
When an invalid or incomplete JSON request body is sent, it returns the 400 status code which is correct. However in the response body, HTML response is also returned as below.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Plug.Parsers.ParseError at POST /payments</title>
<meta name="viewport" content="width=device-width">
<style>/*! normalize.css v4.2.0 | MIT License | github.com/necolas/normalize.css */html{font-family:sans-serif;line-height:1.15;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}body{margin:0}article,aside,details,figcaption,figure,footer,header,main,menu,nav,section{display:block}audio,canvas,progress,video{display:inline-block}audio:not([controls]){display:none;height:0}progress ...
I need to return a custom json response with 400 Bad Request, instead of of the elixir generated HTML, if the request body is invalid invalid.
Could anyone guide, how do I achieve this?