簡體   English   中英

如何從 Spring 引導后端獲取 Axios 中的異常消息

[英]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 中輸入的那個。 我該怎么做呢?

  • 在 Axios 上,您可以訪問“error.response.data”中的錯誤響應正文。
  • 在您的 spring 引導上,我建議使用@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,但您可以根據需要對其進行自定義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM