Ash_s94
Ash_s94

Reputation: 817

Custom Json Error message

I'm trying create an API that returns a Game Object in my controller.
If the logic works successfully it returns a Game Object, if the logic fails I need to return an error message in the form of a json string: {error: "You've lost"}.

My question is: should I create an empty interface that both the Game Class and Error Class implement, so I can just return that interface class in my API, or is there an easier way that I can do this?
Essentially when the game is working I'm returning the Game Obj and when the game is over I need to return an error obj.

Any ideas?

Controller:

@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) 
public Game makeGuess(@RequestBody Guess guess){ 
    return gameService.makeGuess(guess);
}

..Service class does some business logic returning the Game object

Game Class (JavaBean)

public class Game{

private String gameId;

@JsonIgnore
private String word;

private StringBuilder currentWord;
private String status;
private int incorrect;

public Game(String gameId, String word) {
    this.status = "";
    this.gameId = gameId;
    this.word = word;
    currentWord = new StringBuilder();
    for(int i = 0; i <word.length();i++){
        currentWord.append("_");
    }
}

public Game(){}

public String getId() {
    return gameId;
}

public void setId(String gameId) {
    this.gameId = gameId;
}

public int getIncorrect() {
    return incorrect;
}

public void setIncorrect(int incorrect) {
    this.incorrect = incorrect;
}

public void incrementWrong(){
    this.incorrect++;
}

public StringBuilder getCurrentWord() {
    return currentWord;
}

public void setCurrentWord(StringBuilder initialWord) {
    this.currentWord = initialWord;
}

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}

public String getWord() {
    return word;
}

public void setWord(String word) {
    this.word = word;
}

}

Error Class(JavaBean)

package com.hangman.entity;

public class CustomError {

private String error;

public CustomError(String statusMessage) {
    this.error = statusMessage;
}

public String getError() {
    return error;
}

public void setError(String statusMessage) {
    this.error = statusMessage;
}

}

Upvotes: 1

Views: 1142

Answers (1)

starman1979
starman1979

Reputation: 1074

You could throw an exception from your service/controller. Create an ExceptionHandler with @ControllerAdvice annotation, which will catch the exception and return your error object, like so:

@ControllerAdvice
public class GameLostExceptionHandler {

   @ExceptionHandler({GameLostException.class})
   public ResponseEntity<CustomError> gameLostHandler(GameLostException e) {
      return new ResponseEntity<>(new CustomError("Game lost"), HttpStatus.OK);
   }
}

Upvotes: 2

Related Questions