亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何向最終用戶顯示來自 API 的錯誤消息?

如何向最終用戶顯示來自 API 的錯誤消息?

子衿沉夜 2022-09-21 21:40:42
當用戶嘗試上傳不是圖像的文件時,我試圖顯示來自 REST API 的錯誤消息。從 API 返回的 JSON 類似于:{     "publicError": "Could not be uploaded, it is not an image!",     "innerError": "WrongImageTypeException()"     }但我不知道它如何向用戶顯示。我試過了this.setState({ errorMesage: { ...err } })控制臺日志看起來像這樣https://cdn1.imggmi.com/uploads/2019/4/4/f642ed4326147b3f2c6899e78d415771-full.png。如何顯示此響應錯誤消息?后端代碼public ResponseEntity<?> uploadFile(    @RequestHeader(value = "Authorization") String authorizationHeader,    @RequestParam("file") MultipartFile file) throws UserNotFoundException {        try {            if(!(fileStorageService.checkFileType(file))){                throw new WrongImageTypeException();            }        }catch (WrongImageTypeException error){            return ResponseEntity.status(403).body(new ErrorMessageManager(                "Could not be uploaded, it is not an image!",error.toString()));        }前端代碼this.state : {      errorMesage: {        publicError: "",      }, } public uploadHandler() {    const formdata: FormData = new FormData();    formdata.set('file', this.state.avatar);    const config = {      headers: {        'Content-Type': 'multipart/form-data',        'Authorization': `Bearer ${cookies.get('tk879n')}`      }    };    axios.post(      `${serverUrl}/uploadFile`,      formdata,      config    ).then(response => {      this.setState({        userProfile: {          ...this.state.userProfile,          avatarUrl: response.data,        }      });    }    ).catch((err) => {      // i want to set error message state and display in render function      this.setState({ errorMesage: { ...err } });       console.debug(this.state.errorMesage);    });  }爪哇島反應打字腳本彈簧靴
查看完整描述

1 回答

?
滄海一幻覺

TA貢獻1824條經驗 獲得超5個贊

您的顯示對象的結構:console.debug(this.state.errorMesage);

http://img1.sycdn.imooc.com//632b148f0001914411800180.jpg

從結構中,您可以看到 包含您要查找的結構:this.state.errorMesage.response.data


"publicError": "Could not be uploaded, it is not an image!",

"innerError": "WrongImageTypeException()"

修復

所以而不是你應該使用 ????...err...err.response.data



查看完整回答
反對 回復 2022-09-21
  • 1 回答
  • 0 關注
  • 80 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號