【问题标题】:Custom Json Error message自定义 Json 错误消息
【发布时间】:2018-09-02 08:50:17
【问题描述】:

我正在尝试在我的控制器中创建一个返回游戏对象的 API。
如果逻辑成功,它会返回一个游戏对象,如果逻辑失败,我需要以 json 字符串的形式返回错误消息:{error: "You've lost"}。

我的问题是:我应该创建一个游戏类和错误类都实现的空接口,这样我就可以在我的 API 中返回该接口类,还是有更简单的方法可以做到这一点?
基本上,当游戏运行时,我会返回 Game Obj,而当游戏结束时,我需要返回错误 obj。

有什么想法吗?

控制器:

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

..Service 类执行一些返回 Game 对象的业务逻辑

游戏类 (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;
}

}

错误类(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;
}

}

【问题讨论】:

    标签: java json spring-boot error-handling interface


    【解决方案1】:

    您可以从服务/控制器中抛出异常。创建一个带有@ControllerAdvice 注释的ExceptionHandler,它将捕获异常并返回您的错误对象,如下所示:

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

    【讨论】:

    • 基本上,是的。您可以添加一些自定义错误代码,以便您的前端可以以不同方式处理不同的错误(或游戏失败)情况。
    • 当我检查异常时,我会在控制器中返回什么?例如:if(game = "lost"){throw new GameLostExceptionHandler();},我试过了,还是不行
    • 如果我尝试“throw new GameLostException()”,它会说 GameOverException 为 null
    • 是的,您应该抛出异常 (throw new GameLostException())。什么时候说null?如果您使用的是 spring,那么 @ControllerAdvice 注释应该将 GameLostExceptionHandler 注册为异常处理程序,并且应该捕获(或拦截)异常
    猜你喜欢
    • 2016-09-03
    • 1970-01-01
    • 2015-09-21
    • 2011-04-27
    • 2021-09-13
    • 2017-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多