Spring MVC @Controller中如何返回错误消息


问题内容

我正在使用这样的方法

@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<UserWithPhoto> getUser(@RequestHeader(value="Access-key") String accessKey,
                                     @RequestHeader(value="Secret-key") String secretKey){
    try{
        return new ResponseEntity<UserWithPhoto>((UserWithPhoto)this.userService.chkCredentials(accessKey, secretKey, timestamp),
                new HttpHeaders(),
                HttpStatus.CREATED);
    }
    catch(ChekingCredentialsFailedException e){
        e.printStackTrace();
        return new ResponseEntity<UserWithPhoto>(null,new HttpHeaders(),HttpStatus.FORBIDDEN);
    }
}

我想在发生异常时返回一些文本消息,但是现在我只返回状态和空对象。有可能吗?


问题答案:

正如Sotirios Delimanolis在评论中指出的那样,有两种选择:

返回ResponseEntity并显示错误消息

像这样更改您的方法:

@RequestMapping(method = RequestMethod.GET)
public ResponseEntity getUser(@RequestHeader(value="Access-key") String accessKey,
                              @RequestHeader(value="Secret-key") String secretKey) {
    try {
        // see note 1
        return ResponseEntity
            .status(HttpStatus.CREATED)                 
            .body(this.userService.chkCredentials(accessKey, secretKey, timestamp));
    }
    catch(ChekingCredentialsFailedException e) {
        e.printStackTrace(); // see note 2
        return ResponseEntity
            .status(HttpStatus.FORBIDDEN)
            .body("Error Message");
    }
}

注意1
:您不必使用ResponseEntity构建器,但我发现它有助于保持代码的可读性。它还有助于记住特定HTTP状态代码的响应应包含哪些数据。例如,状态码为201的响应应在Location标头中包含指向新创建的资源的链接(请参见状态码定义)。这就是Spring提供便捷构建方法的原因ResponseEntity.created(URI)

注意2 :不要使用printStackTrace(),而是使用记录器。

提供一个 @ExceptionHandler

从您的方法中删除try-catch块,并使其引发异常。然后在带有以下注释的类中创建另一个方法@ControllerAdvice

@ControllerAdvice
public class ExceptionHandlerAdvice {

    @ExceptionHandler(ChekingCredentialsFailedException.class)
    public ResponseEntity handleException(ChekingCredentialsFailedException e) {
        // log exception
        return ResponseEntity
                .status(HttpStatus.FORBIDDEN)
                .body("Error Message");
    }        
}

请注意,使用注释的方法@ExceptionHandler可以具有非常灵活的签名。有关详细信息,请参见Javadoc