【发布时间】:2015-12-03 04:49:55
【问题描述】:
我正在使用这样的方法
@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);
}
}
并且我想在发生异常时返回一些文本消息,但现在我只返回状态和空对象。有可能吗?
【问题讨论】:
-
将您的返回类型更改为
ResponseEntity<Object>或ResponseEntity<?>。不要为您的错误案例传递null参数,而是传递String。 Spring 足够聪明,可以看到String并将其作为文本写入响应正文。或者,提供一个@ExceptionHandler,它将自己处理异常并让您的处理程序抛出异常。 -
@SotiriosDelimanolis,想知道你为什么不创建答案?
-
@lkrnac 我过去回答过类似的问题。我不再觉得它们一定很有趣。但是我找不到重复的,所以我还是想给点东西。
标签: java spring-mvc