我正在使用这样的方法
@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
header 中包含指向新创建资源的链接(参见 Status Code Definitions)。这就是 Spring 提供方便的构建方法 ResponseEntity.created(URI)
的原因。
注意 2:不要使用 printStackTrace()
,而是使用记录器。
提供一个 @ExceptionHandler
从您的方法中删除 try-catch block 并让它抛出异常。然后在使用 @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了解详情。
关于java - 如何在spring mvc @Controller中返回错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32441919/