简体   繁体   中英

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

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.

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;

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM