Using the Play Framework for Java, how do I return a 500 response from a controller?

452 views Asked by At

I've inherited a Play Framework v1.2 application that serves up both a Website as well as an API. The existing error handling strategy for the API controllers uses renderJSON(error.message) to return errors to our client, unfortunately creating responses that return a 200.

I want to return an actual status code, 4xx or 5xx. The problem is if I use error(message), that produces a 500 response, but the 500.html error page kicks in and returns HTML instead of JSON. I could override the template to render JSON but that affects our customer facing web pages.

I'm struggling to figure out how to manually set a response status code only for our API controllers, as well as render a JSON doc.

I'm pretty new to the Framework and have been looking over the docs, but for version 1.2, I don't see a lot of options.

2

There are 2 answers

1
Joshua Belden On

I'm not sure if this is the best solution, but it seems to be the most direct without dealing with the larger issue of mixing a website project with an API project.

I found the source code for the Play Framework version 1.2 here, https://github.com/playframework/play1/tree/1.2.x.

I was able to find the definition of Response and find that status is just a field on the class. So this works as I was hoping:

renderJSON("{ 'status' : 'error' }");
response.status = Http.StatusCode.INTERNAL_ERROR;
0
irxground On

Functions like renderJSON() throws RenderJson exception internally, so the status code have to be set before calling it.

response.status = Http.StatusCode.INTERNAL_ERROR;
renderJSON(theJsonObject);