我会尽量保持简短.这是我在尝试理解Spark过滤器时遇到的问题.我正在尝试创建一个简单的应用程序,它应该做的一件事是每次客户端即将看到一个http错误,例如404或500时创建一个错误报告.这是我的应用程序的样子:
import static spark.Spark.*;
public class MyApp {
public static void main(String[] args) {
get("/hello", (req, res) -> "{\"status\":\"OK\"}");
after((request, response) -> {
if (response.raw().getStatus() == 404) {
// here run the code that will report the error e.g.
System.out.println("An error has occurred!!");
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
出于某种原因,response当我检查它是否设置为404时,参数的status属性设置为0.文档说明了"after" filters are evaluated after each request and can read the request and read/modify the response,我应该能够以某种方式(除非文档错误).
基本上,我试图使用after过滤器拦截http错误但是当我尝试检查响应时,我没有得到我期望的结果.
有谁知道做同样的事情或如何使这项工作的不同方式是什么?
谢谢.
我使用通配符路由解决了这个问题.after我没有调用该方法,而是为每个绑定"*"路由的HTTP方法添加了一条路由.
将它们放在方法的底部非常重要,Main因此如果没有路由得到解决,这些路径总会被触发.
这是一个例子:
import static spark.Spark.*;
public class MyApp {
public static void main(String[] args) {
get("/hello", (req, res) -> "{\"status\":\"OK\"}");
get("*", (request, response) -> {
System.out.println("404 not found!!");
// email me the request details ...
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3862 次 |
| 最近记录: |