响应中的JAX / Jersey自定义错误代码 [英] JAX/Jersey Custom error code in Response

查看:175
本文介绍了响应中的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());
     }

}

现在在你的代码中实现了休息服务你只需要抛出这种类型的新异常,传入构造函数中的文本值,例如

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

这可以为每个Web异常创建一个这样的类,并以类似的方式抛出。

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

这篇关于响应中的JAX / Jersey自定义错误代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆