No function clause matching in String.starts_with?/2

I wrote a function to remove "Bearer " from token as:

def clean_token jwt do
    token= case String.starts_with?(jwt, "Bearer ") do
       false ->
       true ->
         List.last(String.split(jwt, "Bearer "))

When I try to call it:

token= Plug.Conn.get_req_header(conn, “authorization”)
sent_token= MyApp.JWT.clean_token token

, I get this error:

no function clause matching in String.starts_with?/2

But why?

I believe this would happen if jwt is not a binary because of the when is_binary(string) guard clause. Maybe it’s coming back as nil because the authorization header is not set?

Plug.Conn.get_req_header returns a list.

[token] = Plug.Conn.get_req_header(conn, "authorization")  

Note you can simplify your function clean_token as follows:

    def clean_token("Bearer " <> jwt), do: jwt
    def clean_token(jwt), do: jwt

I tried to IO.put the sent token, and its like:


Also, is_binary returned false for the above token.

Please use IO.inspect, it will give you some kind of additional type information in the printout, while IO.puts is meant to print a human readable string representation.

1 Like

Thanks! I did not notice that get_req_header return array :relieved: