How to get the Error in json format if the JWT authentication fails

(First of all sorry for my bad English)

Well, I’m reading the docs about JWT authentication, but I have a problem handling the error when the user is not authenticated or the token is not in the header.

I need to send the errors in Json format because i’m making a api-only adonis project.

I have this

try {
  await auth.check()
} catch (error) {
  return response.json({message: 'Missing or invalid jwt token'})

But I don’t get the json in the reponse of my api, I get a full html page with the error 401 E_INVALID_JWT_TOKEN: jwt must be provided.

How can I send a json response when the user is not athenticated?

Just send your requests with a correct Accept header to get a JSON response.

Accept: application/json

Well i just accept in the headers the content Application/json, but not work, what i can see is that the code never enters to the catch block! i put a consolo log inside and this is not printed in the console, then the auth.check() function is making all the logic.

Any idea?

If auth.check() is not failing, that means it is able to authenticate the user. Are you sure that you are not sending in the correct JWT token? Also, is jwt the default authenticator in your config/auth.js file?

1 Like

I’m going to try to use if else instead try catch, because I think that the auth.check() works to telling us that the user is not authenticated and that’s why my code never enter to the catch block.

I’m not in my computer right now but i post the results later.


It does not work with IF ELSE either, it seems that the auth.check () method does not launch the catch if the JWT is wrong or does not exist. Then I’m not able to handle the error by myself, to send a JSON Response to the client.

i have face same issue . if i try to put if else then it’s not working it’s going in catch block.