简体   繁体   English

使用 Play Framework for Java,如何从控制器返回 500 响应?

[英]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.我继承了一个 Play Framework v1.2 应用程序,它同时提供网站和 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. API 控制器的现有错误处理策略使用renderJSON(error.message)向我们的客户端返回错误,不幸的是创建了返回 200 的响应。

I want to return an actual status code, 4xx or 5xx.我想返回一个实际的状态码,4xx 或 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.问题是如果我使用error(message) ,会产生 500 响应,但 500.html 错误页面会启动并返回 HTML 而不是 JSON。 I could override the template to render JSON but that affects our customer facing web pages.我可以覆盖模板来呈现 JSON,但这会影响我们面向客户的网页。

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.我正在努力弄清楚如何仅为我们的 API 控制器手动设置响应状态代码,以及呈现 JSON 文档。

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.我对框架很陌生,并且一直在查看文档,但是对于 1.2 版,我没有看到很多选项。

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.我不确定这是否是最好的解决方案,但它似乎是最直接的,无需处理将网站项目与 API 项目混合的更大问题。

I found the source code for the Play Framework version 1.2 here, https://github.com/playframework/play1/tree/1.2.x .我在这里找到了 Play Framework 1.2 版的源代码, 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.我能够找到Response的定义,并发现 status 只是类上的一个字段。 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.renderJSON()这样的函数在内部会抛出RenderJson异常,所以在调用它之前必须设置状态码。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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