How to catch the Error message coming from Spring in react

I’m trying to catch the error this error message from my Rest controller in spring

@GetMapping
public List<Student> getAllStudent() {
  throw new IllegalStateException("Opps can not get all students");
  // return studentService.getAllStudents();
}

The error is catch in react this way, what I’m trying to do is to show in the console the Error message

import fetch from "unfetch";

const checkStatus = (response) => {
  if (response.ok) {
    return response;
  } else {
    let error = new Error(response.statusText);
    error.response = response;
    response.json().then((e) => {
      error.error = e;
    });
    return Promise.reject(error);
  }
};

export const getAllStudents = () =>
  fetch("http://localhost:1020/api/students").then(checkStatus);

And then is consume by this method to show it in the console

const fetchAllStudents = () => {
  this.setState({
    isFetching: true,
  });
  getAllStudents()
    .then((res) =>
      res.json().then((students) => {
        console.log(students);
        this.setState({
          students,
          isFetching: false,
        });
      })
    )
    .catch((error) => {
      console.log(error.error.message);
      //  const message =error.error.message;
      //   errorNotification(message,message)
      this.setState({
        isFetching: false,
      });
    });
};

The problem is that I get is that “message” is undefined I want to log “Opps can not get all students” in the console:

Picture of the problem

Answer

Add this line to your application.properties file:

server.error.include-message=always

And try throwing ResponseStatusException, so that you give a HTTP Status, together with the message, and not just 500 Server Error.

Like this:

throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Your Message...");