ResponseEntity и JavaScript - как получить пользовательское сообщение об ошибке - PullRequest
0 голосов
/ 30 сентября 2019

Интересно, как лучше всего получить сообщение с сервера (Spring Boot) и отобразить его во внешнем интерфейсе (Vue JS, ES6).

Backend (мой единственный подход с успехом - передать сообщение об ошибке)в заголовке, но, может быть, есть лучшее решение?):

public ResponseEntity<?> getOneReport(@PathVariable Long incidentId) {

...

    HttpHeaders header = new HttpHeaders();
    header.setContentType(MediaType.TEXT_PLAIN);
    header.set("text", "My custom error message");
    return ResponseEntity.notFound()
            .headers(header)
            .build();

Фронтенд:

axios.get(...)
.then(...)
.catch((error) => {
      console.log(error.headers.text);

Я попытался передать свое пользовательское сообщение об ошибке от сервиса к клиенту, как это:

return new ResponseEntity<Object>(
                "My custom error message that I want to display in frontend", new HttpHeaders(), HttpStatus.FORBIDDEN);

но я не знаю, как прочитать это сообщение от моего клиента (ES6 / Vue js):

.catch((error) => {
                        console.log(error.error);

или

.catch((error) => {
                        console.log(error.response.data); -> I get Blob {size: 59, type: "text/plain"}

1 Ответ

0 голосов
/ 30 сентября 2019

вы пробовали с response.headers?

axios.get(...)
   .then(response){
         console.log(response.headers)
      }
   .catch((error) => {
         console.log(error.headers.text);

Вот документация: https://github.com/axios/axios#response-schema

...