2017-10-19 87 views
-1

我希望我的服務器向angular js客戶端發送指示性錯誤。角度js無法解析jax-rs響應

我看到這些例子:

Example 7 
Project: spice File: RequestService.java View source code 6 votes vote down vote up 
@GET 
@Path("date") 
@Produces("text/plain") 
public Response get(@Context Request request) { 
    final Date modificDate = getLastModificationDateFromDatastore(); 
    final EntityTag entityTag = getEntityTagFromDatastore(); 
    final ResponseBuilder resp = request.evaluatePreconditions(modificDate, 
      entityTag); 
    if (resp != null) { 
     return resp.build(); 
    } 
    // Build new Response 
    final ResponseBuilder responseBuilder = Response.status(200); 
    responseBuilder.entity("This is the Entity from " + modificDate); 
    responseBuilder.lastModified(modificDate); 
    responseBuilder.tag(entityTag); 
    return responseBuilder.build(); 
} 

Example 8 
Project: zeppelin File: JsonResponse.java View source code 4 votes vote down vote up 
public javax.ws.rs.core.Response build() { 
    ResponseBuilder r = javax.ws.rs.core.Response.status(status).entity(this.toString()); 
    if (cookies != null) { 
    for (NewCookie nc : cookies) { 
     r.cookie(nc); 
    } 
    } 
    return r.build(); 
} 

但是當我的服務器代碼發送:

catch (Exception ex) 
{ 

    String error = "RuntimeException: test11"; 
    logger.error("update voice filed. Error: "+error); 

    return Response.serverError().entity(error).build(); 
} 

在客戶端的代碼,我無法找到此錯誤消息:

  $http.put('api/foo', {voice : voice, isAddMode : isAddMode}).then(
       function successCallback(response) { 
.. 
       }, function errorCallback(response) { 
        var responseStr = JSON.stringify(response) 
        console.log(responseStr); 
        deferred.reject(responseStr); 
       }); 

我得到解析錯誤,但總的來說我無法在js中找到合適的成員。

SyntaxError: Unexpected token R in JSON at position 0 
    at JSON.parse (<anonymous>) 
    at fromJson (angular.js:1377) 
    at defaultHttpResponseTransform (angular.js:11003) 
    at angular.js:11094 
    at forEach (angular.js:357) 
    at transformData (angular.js:11093) 
    at transformResponse (angular.js:11914) 
    at processQueue (angular.js:16648) 
    at angular.js:16692 
    at Scope.$eval (angular.js:17972) 
+0

Angular試圖解析'RuntimeException:test11'這是無效的JSON –

回答

0

,我不得不刪除在服務器端的"Produces"註釋:

@Path("/foo") 
    @PUT 
    @Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8") 
// @Produces(MediaType.APPLICATION_JSON + ";charset=utf-8") 

然後JSON對象從服務器發送的並不僅僅是字符串。