Return exception from JAX-RS Rest Service as JSON

本小妞迷上赌 提交于 2019-12-30 11:34:33

问题


Is it in some way possible that an exception thrown from a rest service is returned as JSON? I have a JAX-RS Rest Service where I would like to achieve this. When I throw it now, it's mapped to an HTML response, which is not what i want. From what I have understood an ExceptionMapper will also map it to HTML? Is there any other alternative or libraries that allows the exception to be returned in JSON format?


回答1:


It will respond as 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;
    }
}



回答2:


You can create custom exception,It takes JSON request and response

    @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

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

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



回答3:


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)




回答4:


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"
}

}



来源:https://stackoverflow.com/questions/36467648/return-exception-from-jax-rs-rest-service-as-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!