1

I am working on a Chess game that I built in Spring and then connected to React. I have custom exceptions in Spring that work perfectly in the backend but I can't figure out how to catch my custom message in the front end.

I can use Postman to make a move with the program and if it is an illegal move I will receive this message-

Status Code: 417 Expectation Failed Message: That is not a legal move for a PAWN at uri=/game;client=127.0.0.1

However, in React, the only message(besides from xhr.js:178) I get is-

Request failed with status code 417

I attempted to follow the advice from here - How to show server (Java) Exception message in React.js and here- How to throw an exception back in JSON in Spring Boot since my response is not in JSON format (even though I thought @ResponseBody was supposed to convert it to JSON) but after attempting to follow the accepted answer, it only resulted in an Error that was not resolved and React instead said it failed with status code 500 so I am obviously missing something.

Here is my original CustomerExceptionsHandler-

package com.chess.exceptions;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@ControllerAdvice
public class CustomExceptionsHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = InvalidMoveException.class)
    @ResponseBody
    protected ResponseEntity<Object> resolveInvalidMove(InvalidMoveException e, WebRequest req){   
        ErrorResponse errorResponse = new ErrorResponse(HttpStatus.EXPECTATION_FAILED.value(),
                HttpStatus.EXPECTATION_FAILED.getReasonPhrase(),
                e.getMessage(),
                req.getDescription(true));
        return handleExceptionInternal(e, errorResponse.toString(), new HttpHeaders(), HttpStatus.EXPECTATION_FAILED, req);       
    }

Here are my two attempts to modify my resolveValidMove method to return JSON-

ATTEMPT 1
  @ExceptionHandler(value = InvalidMoveException.class)
  @ResponseBody
  @ResponseStatus(HttpStatus.EXPECTATION_FAILED)
  public ErrorResponse resolveInvalidMove(InvalidMoveException e){
       return new ErrorResponse(417, e.getMessage());
   }

ATTEMPT 2

@ExceptionHandler(value = InvalidMoveException.class)
 @ResponseBody
    public ErrorResponse resolveInvalidMove(InvalidMoveException e, WebRequest req){
        ErrorResponse errorResponse = new ErrorResponse(HttpStatus.EXPECTATION_FAILED.value(),
                HttpStatus.EXPECTATION_FAILED.getReasonPhrase(),
                e.getMessage(),
                req.getDescription(true));      
        return errorResponse;

ErrorResponse.java

package com.chess.exceptions;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "error")
public class ErrorResponse {
    private int status;
    private String errReason;
    private String errMessage;
    private String path;

    public ErrorResponse(int status, String errReason, String errMessage, String path) {
        this.status = status;
        this.errReason = errReason;
        this.errMessage = errMessage;
        this.path = path;
    }
   //2nd constructor added for ATTEMPT 1
    public ErrorResponse(int status, String errMessage){
        this.status = status;
        this.errMessage = errMessage;
    }

    @Override
    public String toString(){
        return "Status Code: "  + status + " " + errReason + " Message: " + errMessage + " at " + path;
    }
}

Here is the relevant code from React- Board.js

 DataService.makeMove(move)
            .then(res => {
                //console.log(res.data);
                setIsWhite((prev) => !prev);                
                props.setTheBoard(res.data);
                setStatus(res.data[64]);
                updateMovesList();
            })
            .catch(err => {
                console.log(err)                
                console.log(err.message)                
            })

DataService.js

makeMove(move){
        return axios.post(`${url}`, move);
    }

Any help would be appreciated

rainmaker
  • 250
  • 1
  • 10

0 Answers0