2017-07-03 144 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

感謝您的解釋和解決方案。我嘗試了一種不同的方式,但你的解決方案也可以工作。我接受它作爲解決方案。 :) –