【问题标题】:How to display exception message from springboot on angular application如何在角度应用程序上显示来自springboot的异常消息
【发布时间】:2020-04-16 16:34:31
【问题描述】:

我正在研究 Spring Boot + Angular 集成,我想知道如何在我的 Angular 应用程序中显示异常消息。我在 Spring Boot 中创建了异常处理程序类,如下所示:

@ControllerAdvice
public class ExceptionController {

@ExceptionHandler(value={CommonException.class})
public ResponseEntity<Object> noResult(CommonException e){
    HttpStatus status=HttpStatus.BAD_REQUEST;       
    return new ResponseEntity<Object>(new CustomExceptionPayload(e.getMessage(),"400"), status);
}
}

在角度方面,我使用 httpclient 通过服务类发送请求,如下所示:

public generatFile(file:any,to:string,from:string,proj_name:string,count:string,env:string,event:string){
    console.log("in service");
    const formData=new FormData();
    formData.append('file',file);
    formData.append('to',to);
    formData.append('from',from);
    formData.append('proj_name',proj_name);
    formData.append('event',event);
    formData.append('env',env);
    formData.append('count',count);

    return this.http.post(this.baseUrl+'/events',formData,{
        observe: 'response',
        responseType: 'blob' as 'json'
      }
    );
}

在我的主要组件中接收这样的响应:

this.service.generatFile(this.file,new Date(this.to).toLocaleDateString(),new Date(this.from).toLocaleDateString(),this.proj_name,this.count,this.env,this.event).subscribe((resp: any) => {
    const blob = new Blob([resp.body], { type: resp.headers.get('Content-Type') });
    saveAs(blob, this.fileName);
    this.loading=false;
  },((error:any) =>{
    this.message=error.message;
    this.loading=false;
  }

我在 Angular 中使用 error.message 来获取上面给出的错误消息,但它不起作用。

当我使用邮递员时,我得到以下回复:

{
"message": "number of events per file is greater than number of failed events",
"status": "400"
}

我不知道如何获得与我从 Spring Boot 发送的 Angular 相同的错误消息。如果有人能提供代码答案,我将不胜感激。

【问题讨论】:

    标签: java angular spring spring-boot exception


    【解决方案1】:

    您可以使用 observable 中的 error 对象。

    this.service.generatFile().subscribe(
        (res) => {
            // handle response
        }, (err) => {
            // handle errors
        });
    

    【讨论】:

    • 我更新了我的代码并使用了 error.message(见上文),但它没有用。你知道如何访问错误响应正文吗?
    • 我更新了我的代码并使用了 error.message(见上文),但它没有用。你知道如何访问错误响应正文吗?
    猜你喜欢
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-21
    • 2017-02-25
    相关资源
    最近更新 更多