如何在spring mvc @Controller中返回错误信息 [英] How return error message in 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);
}
}
我想在发生异常时返回一些短信但现在我只返回status和null对象。有可能吗?
And I want to return some text message when exception occurs but now I just return status and null object. Is it possible to do?
推荐答案
作为 Sotirios Delimanolis 已在评论中指出,有两种选择:
As Sotirios Delimanolis already pointed out in the comments, there are two options:
更改您的方法如下:
@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)
。
Note 1: You don't have to use the ResponseEntity
builder but I find it helps with keeping the code readable. It also helps remembering, which data a response for a specific HTTP status code should include. For example, a response with the status code 201 should contain a link to the newly created resource in the Location
header (see Status Code Definitions). This is why Spring offers the convenient build method ResponseEntity.created(URI)
.
注意2 :不要使用 printStackTrace()
,而是使用记录器代替。
Note 2: Don't use printStackTrace()
, use a logger instead.
删除从你的方法try-catch块让它抛出异常。然后在使用 @ControllerAdvice
注释的类中创建另一个方法,如下所示:
Remove the try-catch block from your method and let it throw the exception. Then create another method in a class annotated with @ControllerAdvice
like this:
@ControllerAdvice
public class ExceptionHandlerAdvice {
@ExceptionHandler(ChekingCredentialsFailedException.class)
public ResponseEntity handleException(ChekingCredentialsFailedException e) {
// log exception
return ResponseEntity
.status(HttpStatus.FORBIDDEN)
.body("Error Message");
}
}
请注意使用<$ c $注释的方法c> @ExceptionHandler 可以拥有非常灵活的签名。请参阅 Javadoc 了解详情。
Note that methods which are annotated with @ExceptionHandler
are allowed to have very flexible signatures. See the Javadoc for details.
这篇关于如何在spring mvc @Controller中返回错误信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!