如何显示从API到最终用户的错误消息?

时间:2019-04-03 22:41:58

标签: java reactjs typescript spring-boot

当用户尝试上传不是图像的文件时,我正在尝试显示来自REST API的错误消息。

从API返回的JSON与此类似:

{
    "publicError": "Could not be uploaded, it is not an image!",
    "innerError": "WrongImageTypeException()"
}

但是我不知道它如何显示给用户。

我尝试了

this.setState({ errorMesage: { ...err } }) 

控制台日志看起来像这样Console log 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 个答案:

答案 0 :(得分:0)

您的console.debug(this.state.errorMesage);显示了对象的结构:

enter image description here

从结构中您可以看到this.state.errorMesage.response.data包含您要寻找的结构:

"publicError": "Could not be uploaded, it is not an image!",
"innerError": "WrongImageTypeException()"

修复

因此,您应该使用...err而不是...err.response.data