2017-07-03 120 views
1

我的春天启动控制器的方法:处理错误响应React.js

@RequestMapping(value = "/test", method = RequestMethod.POST) 
    @ResponseBody 
    public ResponseEntity<APIResponseMessage> testMethod(@RequestBody MyPojo myPojo) { 
     APIResponseMessage resp = new APIResponseMessage(); 
     try { 
      serviceObj.callServiceMethod(myPojo); 
      resp.setMessage("successfull!"); 
     } catch (Exception e) { 
      resp.setMessage("failed!"); 
      return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(resp); 
     } 
     return ResponseEntity.ok(resp); 
    } 

行动作出反应处理类有以下方法:

export default (data) => (dispatch) => { 
    dispatch({ 
    type: initHandler 
    }); 

    fetchJSON(url, 'POST', data) 
    .then((json) => { 
     dispatch({ 
     type: successHandler, 
     apiResponse: json 
     }) 
    }) 
    .catch((error) => { 
     dispatch({ 
     type: failureHandler, 
     apiResponse: error, 
     apiMessage : "System encountered error. Please try again later." 
     }) 
    }) 
} 

而且fetchJSON被定义在我的util类中的一个反应作为:

export const checkStatus = response => { 
    const hasError = (response.status < 200 || response.status >= 300) 
    if (hasError) { 
    const error = new Error("This is an error") // I want to set my message that I obtained from the controller here. 
    throw error 
    } 
    return response 
} 

export const parseJSON = response => response.json() 

export const fetchJSON = (url, method, data) => { 
    return fetch(url, { 
    method: method, 
    headers: new Headers({ 
     'Content-Type': 'application/json' 
    }), 
    body: JSON.stringify(data) 
    }).then(checkStatus).then(parseJSON); 
} 

我想将我从我的API获得的自定义消息设置为erro r对象。我尝试了很多选择,但无法使其工作。

回答

1

问题在于如何解决Promise问题,或者更确切地说,在您尝试使用Promise时未解决问题。对'response.json()'的调用返回一个承诺,在正常的执行流程中,当你不'抛出'错误时,这个承诺已经解决,你可以使用结果。

但是,当引发错误时,您需要解析或'.then()'catch块中的错误。

我认为这应该为你工作,先扔你response.text()中的checkStatus功能:

if (hasError) { 
    throw response.json() 
} 

因为你是在一个承诺,最近抓抛出一个错误,或拒绝回调引用:

.catch((error) => { 
    dispatch({ 
    type: failureHandler, 
    apiResponse: error, 
    apiMessage : "System encountered error. Please try again later." 
    }) 
}) 

“错误”在这种情况下是通过调用“response.text()”创建的未解决的承诺,这样你就可以通过包装在error.then(在“调度”解决此),如下所示:

.catch((error) => { // error is a Promise 
    error.then((e) => { 
     dispatch({ 
      type: failureHandler, 
      apiResponse: e, // e is now the resolved value of 'response.text()' 
      apiMessage : "System encountered error. Please try again later." 
     }); 
    }); 
}) 

还有就是这这里的简化的jsfiddle:https://jsfiddle.net/LLL38vea/

+0

我控制器返回JSON对象。 {message:“我的错误消息”}。问题在于,当我希望在'checkStatus'函数中使用这个响应对象时,承诺还没有完成(仍处于未决状态)。所以我不能玩它,直到响应返回到'fetchJSON'函数。 –

+0

我明白你的意思了,问题是未解决的承诺,我更新了我的答案,上面我认为应该解决你的问题 –

+0

感谢您的解释和解决方案。我尝试了一种不同的方式,但你的解决方案也可以工作。我接受它作为解决方案。 :) –