英文:
How to get exception message in Axios from a Spring boot backend
问题
我在使用Spring Boot作为后端,React作为前端。API调用使用axios。现在在Spring Controller中,我处理异常并抛出另一个异常供React提取消息(我真的需要这个消息)。但我得到的只是“Request failed with status code 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”组件,我经常重用它。并且从每个相关组件中将删除方法作为属性传递。
以下是来自Settings组件的部分:
<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}
/>
而在Settings中发送的Deleteitem方法是:
deleteItem = async () => {
await SettingsApiService.delete(this.state.selectedId);
};
在Table组件中,我使用以下按钮进行删除:
<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();
}}
>
删除
</Button>
我希望e.message是我在Controller中抛出的异常消息。我应该如何做到这一点?
英文:
I use a spring boot back with react front. Api calls are with axios. Now in Spring Controller I handle exceptions and throw another one for React to extract a message from (I really need this message). But all i get is "Request failed with status code 500". How can I get this message?
My 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());
}
Now I have a "Table" component which i reuse a lot. And send the deletion method as a prop from every respecting component.
This one is from the Settings component
<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}
/>
And the Deleteitem method in Settings I send is:
deleteItem = async () => {
await SettingsApiService.delete(this.state.selectedId);
};
And in Table component I delete with a button like this:
<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>
I want the e.message to be the one I threw in Controller. How do I do this?
答案1
得分: 4
- 在 Axios 中,你可以通过 "error.response.data" 访问错误响应的主体内容。
- 在你的 Spring Boot 项目中,我建议使用 @ControllerAdvice 来根据你的需求定制响应。
一个示例:
@ExceptionHandler(MyCustomException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public MyCustomResponse myCustomException(MyCustomException e) {
return new MyCustomResponse(e.getStatusCode(), e.getStatusMessage());
}
- 所以按照这个示例,在你的代码中,你会抛出一个 MyCustomException,然后你会在 @ControllerAdvice 组件中拦截它,并以 JSON 格式返回一个 MyCustomResponse。
你定制的响应主体将会类似于这样:
{ "statusCode": 1002, "statusMessage": "My custom error message" }
因此,既然你在响应中返回了这个主体,你可以在 Axios 中通过 "error.response.data.statusMessage" 来访问它。
请注意,在示例中,HTTP 状态码(@ResponseStatus)被设置为 500,但你可以根据你的需求进行自定义。
英文:
- On Axios you can access the body of the error response in "error.response.data".
- On your spring boot I recommend to use @ControllerAdvice to customize your response according to your needs.
An example:
@ExceptionHandler(MyCustomException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public MyCustomResponse myCustomException(MyCustomException e) {
return new MyCustomResponse(e.getStatusCode(), e.getStatusMessage());
}
- So following the example, in your code you will throw a MyCustomException, then you will intercept it in your @ControllerAdvice component and you will return in a JSON format a MyCustomResponse.
Your custom response body will look something like this:
{ statusCode: 1002, statusMessage: "My custom error message" }
So now that you are returning this body on the response you can access it on your axios on "error.response.data.statusMessage".
Please check that on the example the http status code (@ResponseStatus) is set to 500, but you can customize it to your requirement.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论