响应中的 JAX/Jersey 自定义错误代码
在泽西岛,我们如何替换"与已知状态代码相关的状态字符串?
In Jersey, how can we 'replace' the status string associated with a known status code?
例如
return Response.status(401).build();
生成包含以下内容的 HTTP 响应:
generates a HTTP response that contains:
HTTP/1.1 401 Unauthorized
我(不是我,而是客户端应用程序)希望看到响应为:
I (not me, but the client application) would like to see the response as:
HTTP/1.1 401 Authorization Required
我尝试了以下方法但徒劳无功:
I tried the following approaches but in vain:
1) 这只是在 HTTP 响应的正文中添加字符串
1) This just adds the String in the body of the HTTP response
return Response.status(401).entity("Authorization Required").build();
2) 同样的结果:
ResponseBuilder rb = Response.status(401);
rb = rb.tag("Authorization Required");
return rb.build();
感谢您的帮助!
-spd
推荐答案
要在 Jersey 中执行此操作,您需要使用 WebApplicationException 类的概念.一种方法是简单地扩展此类和所有一种方法来设置返回的错误文本.在您的情况下,这将是:
To do this in Jersey you have the concept of WebApplicationException class. One method is to simply extend this class and all one of the methods to set the error text that is returned. In your case this would be:
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import javax.ws.rs.core.Response.*;
public class UnauthorizedException extends WebApplicationException {
/**
* Create a HTTP 401 (Unauthorized) exception.
*/
public UnauthorizedException() {
super(Response.status(Status.UNAUTHORIZED).build());
}
/**
* Create a HTTP 404 (Not Found) exception.
* @param message the String that is the entity of the 404 response.
*/
public UnauthorizedException(String message) {
super(Response.status(Status.UNAUTHORIZED).entity(message).type("text/plain").build());
}
}
现在,在实现 rest 服务的代码中,您只需抛出这种类型的新异常,在构造函数中传递文本值,例如
Now in your code that implements the rest service you would simply throw a new exception of this type, passing in the text value in the constructor e.g.
throw new UnauthorizedException("Authorization Required");
这可以为您的每个网络异常创建一个这样的类并以类似的方式抛出.
That can create a class like this for each of your web exceptions and throw in a similar fashion.
这在 Jersey 用户指南中也有解释 - 尽管代码实际上略有错误:
This is also explained in the Jersey user guide - although the code is actually slightly incorrect:
https://jersey.github.io/nonav/documentation/latest/user-guide.html/#d4e435
相关文章