如何从Spring Boot后端中的Axios获取异常消息

huangapple go评论124阅读模式
英文:

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(&quot;/{id}&quot;)
public ResponseEntity&lt;?&gt; delete(@PathVariable(&quot;id&quot;) Integer id) throws RuntimeException {
log.info(&quot;Request for delete settings {}&quot;, id);
try{
Settings settings = settingsService.findById(id);
settingsService.delete(settings.getId());
log.info(&quot;SUCCESS: {} deleted.&quot;, settings.getId());
return new ResponseEntity&lt;&gt;(settings.getId() + &quot; deleted successfully.&quot;, HttpStatus.NO_CONTENT);
} catch (RuntimeException e) {
System.out.println(&quot;CAUSE Controller: &quot;+e.getCause().getMessage());
throw new RuntimeException(&quot;Error during deletion: &quot; + 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

 &lt;Table
ref=&#39;table&#39;
getTr={this.getTr()}
getUrl={this.getUrl(idType)}
columns={this.getColumns()}
updateSelectedItem={this.updateSelectedItem}
deleteItem={this.deleteItem}
isSettings={true}
showDelete={showDelete}
toggleShowDelete={this.toggleShowDelete}
/&gt;

And the Deleteitem method in Settings I send is:

deleteItem = async () =&gt; {
await SettingsApiService.delete(this.state.selectedId);
};

And in Table component I delete with a button like this:

&lt;Button
variant=&#39;primary&#39;
onClick={() =&gt; {
globalProps
.deleteItem()
.then((res) =&gt; {
console.log(res);
table.draw();
})
.catch((e) =&gt; {
console.log(e);
this.setState({ error: e.message });
this.setState({ showModalBatch: true });
});
this.props.toggleShowDelete();
}}
&gt;
Delete
&lt;/Button&gt;

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: &quot;My custom error message&quot; }

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.

huangapple
  • 本文由 发表于 2020年7月27日 02:56:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/63104384.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定