简体   繁体   English

从JAX-RS Rest Service作为JSON返回异常

[英]Return exception from JAX-RS Rest Service as JSON

Is it in some way possible that an exception thrown from a rest service is returned as JSON? 从REST服务抛出的异常是否以某种方式作为JSON返回? I have a JAX-RS Rest Service where I would like to achieve this. 我有一个JAX-RS Rest Service,我想实现这一目标。 When I throw it now, it's mapped to an HTML response, which is not what i want. 当我现在扔它时,它被映射到HTML响应,这不是我想要的。 From what I have understood an ExceptionMapper will also map it to HTML? 据我了解,ExceptionMapper还将其映射到HTML吗? Is there any other alternative or libraries that allows the exception to be returned in JSON format? 是否有其他替代方法或库允许以JSON格式返回异常?

It will respond as JSON. 它将以JSON响应。

@Provider
@Singleton
public class ExceptionMapperProvider implements ExceptionMapper<Exception>
{

    @Override
    public Response toResponse(final Exception exception)
    {
            return Response.status(HttpStatusCodes.STATUS_CODE_SERVER_ERROR).entity(new BasicResponse(InternalStatus.UNHANDLED_EXCEPTION, exception.getMessage())).type(MediaType.APPLICATION_JSON).build();    
    }
}

@XmlRootElement
public class BasicResponse {

    public String internalStatus;

    public String message;

    public BasicResponse() {}

    public BasicResponse(String internalStatus, String message){
        this.internalStatus = internalStatus;
        this.message = message;
    }
}

You can create custom exception,It takes JSON request and response 您可以创建自定义异常,它需要JSON请求和响应

    @POST
    @Path("/betRequest")
    @Consumes({ "application/json", "application/x-www-form-urlencoded" })
    @Produces({ "application/json", "application/x-www-form-urlencoded" })
    public Response getBetRequest(String betRequestParams, @Context HttpServletRequest request) 
    {
      BetResponseDetails  betResponseDetails = new BetResponseDetails();
      try{
           //you code here
          }
      catch (JSONException ex) 
         {
            ex.printStackTrace();
            betResponseDetails.setResponseCode("9002");//your custom error code
            betResponseDetails.setResponseStatus("Bad Request");//custom status
            betResponseDetails.setResponseMessage("The request body contained invalid JSON");//custom error massage
            return Response.status(200).entity(betResponseDetails).build();
        }
     }

Create One POJO BetResponseDetails 创建一个POJO BetResponseDetails

public class BetResponseDetails {
    private String ResponseStatus;
    private String ResponseCode;
    private String ResponseMessage;

  // getter/setter
 .......
}

catch your exceptions, then build a response object in a standardized format such as 捕获异常,然后以标准化格式构建响应对象,例如

error: {
    code: 'XXX',
    status: HTTPStatus,
    message: 'my error message'
}

And send it as a response with an error status (from Response.Status, usually 4xx or 5xx) 并将其作为带有错误状态的响应发送(来自Response.Status,通常为4xx或5xx)

get the response data in a structure with status and data, if the status is error, show the correct message. 在具有状态和数据的结构中获取响应数据,如果状态为错误,则显示正确的消息。 you can try this way 你可以这样尝试

{
"status": "error",
"data": {
    "message": "information of error message"
}

} }

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

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