Ant*_*s42 5 java error-handling servlet-3.0 jakarta-ee
我有一个在 Jboss 7 (EAP 6.4) 上运行的 EE6 JAX-RS 应用程序,并通过ExceptionMapper
.
不过,在某些情况下(最明显的是当 HTTP 基本身份验证失败时),由于错误发生在调用应用程序之前,因此不会调用此方法,因此客户端会获取服务器的默认错误页面(JBWEB bla bla,具有难看的紫色的 HTML) )。
现在为了捕获这些“外部”错误,我添加了<error-page>
定义,web.xml
如下所示:
<error-page>
<location>/error.json</location>
</error-page>
<error-page>
<error-code>401</error-code>
<location>/error401.json</location>
</error-page>
Run Code Online (Sandbox Code Playgroud)
该位置工作正常,我几乎得到了我想要的响应,但 HTTP 状态代码始终为 200。
至少可以说,这很烦人。如何让错误页面返回正确的错误代码?
我最终编写了一个小型 Web 服务(而不是静态页面),它将为我提供 JSON 响应和正确的 HTTP 状态代码,以及相关标头:
<error-page>
<error-code>401</error-code>
<location>/error/401</location>
</error-page>
Run Code Online (Sandbox Code Playgroud)
哪个调用该服务
@Path("/error")
public class ErrorService {
private static final Map<Integer, String> statusMsg;
static
{
statusMsg = new HashMap<Integer, String>();
statusMsg.put(401, "Resource requires authentication");
statusMsg.put(403, "Access denied");
statusMsg.put(404, "Resource not found");
statusMsg.put(500, "Internal server error");
}
@GET
@Path("{httpStatus}")
public Response error(@PathParam("httpStatus") Integer httpStatus) {
String msg = statusMsg.get(httpStatus);
if (msg == null)
msg = "Unexpected error";
throw new MyWebApplicationException.Builder()
.status(httpStatus)
.addError(msg)
.build();
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个异常类MyWebApplicationException
,它有自己的构建器模式,我之前已经使用它使用 jax-rs 将各种应用程序错误格式化为 JSON ExceptionMapper
。
所以现在我也只是通过同一通道手动输入外部捕获的错误(例如 JAX-RS 外部发生的 401)。
归档时间: |
|
查看次数: |
2075 次 |
最近记录: |