[英]How to get exception message in Axios from a Spring boot backend
我使用 spring 后備箱和反應前板。 Api 調用與 axios。 現在在 Spring Controller 中,我處理異常並拋出另一個異常以供 React 從中提取消息(我真的需要此消息)。 但我得到的只是“請求失敗,狀態碼為 500”。 我怎樣才能得到這個消息? 我的 controller:
@DeleteMapping("/{id}")
public ResponseEntity<?> delete(@PathVariable("id") Integer id) throws RuntimeException {
log.info("Request for delete settings {}", id);
try{
Settings settings = settingsService.findById(id);
settingsService.delete(settings.getId());
log.info("SUCCESS: {} deleted.", settings.getId());
return new ResponseEntity<>(settings.getId() + " deleted successfully.", HttpStatus.NO_CONTENT);
} catch (RuntimeException e) {
System.out.println("CAUSE Controller: "+e.getCause().getMessage());
throw new RuntimeException("Error during deletion: " + e.getCause().getMessage());
}
}
SettingsApiService.js:
delete(id) {
return axios.delete(`${BASE_URL}/${id}`, ApiService.getAuthHeader());
}
現在我有一個“表格”組件,我經常重復使用它。 並將刪除方法作為每個相關組件的道具發送。 這個來自設置組件
<Table
ref='table'
getTr={this.getTr()}
getUrl={this.getUrl(idType)}
columns={this.getColumns()}
updateSelectedItem={this.updateSelectedItem}
deleteItem={this.deleteItem}
isSettings={true}
showDelete={showDelete}
toggleShowDelete={this.toggleShowDelete}
/>
我發送的設置中的 Deleteitem 方法是:
deleteItem = async () => {
await SettingsApiService.delete(this.state.selectedId);
};
在表格組件中,我使用這樣的按鈕刪除:
<Button
variant='primary'
onClick={() => {
globalProps
.deleteItem()
.then((res) => {
console.log(res);
table.draw();
})
.catch((e) => {
console.log(e);
this.setState({ error: e.message });
this.setState({ showModalBatch: true });
});
this.props.toggleShowDelete();
}}
>
Delete
</Button>
我希望 e.message 是我在 Controller 中輸入的那個。 我該怎么做呢?
一個例子:
@ExceptionHandler(MyCustomException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public MyCustomResponse myCustomException(MyCustomException e) {
return new MyCustomResponse(e.getStatusCode(), e.getStatusMessage());
}
您的自定義響應正文將如下所示:
{ statusCode: 1002, statusMessage: "My custom error message" }
因此,現在您在響應中返回此正文,您可以在 axios 上的“error.response.data.statusMessage”上訪問它。
請檢查示例中的 http 狀態代碼 (@ResponseStatus) 是否設置為 500,但您可以根據需要對其進行自定義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.