Java spring mvc @Controller 如何返回错误信息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32441919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How return error message in spring mvc @Controller
提问by user3378876
I am using methods like this
我正在使用这样的方法
@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);
}
}
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?
我想在发生异常时返回一些文本消息,但现在我只返回状态和空对象。有可能吗?
采纳答案by hzpz
As Sotirios Delimanolisalready pointed out in the comments, there are two options:
正如Sotirios Delimanolis已经在评论中指出的那样,有两种选择:
Return ResponseEntity
with error message
返回ResponseEntity
错误信息
Change your method like this:
像这样改变你的方法:
@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");
}
}
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)
.
注 1:您不必使用ResponseEntity
构建器,但我发现它有助于保持代码的可读性。它还有助于记住特定 HTTP 状态代码的响应应包含哪些数据。例如,状态代码为 201 的响应应在Location
标头中包含指向新创建资源的链接(请参阅状态代码定义)。这就是 Spring 提供方便的构建方法的原因ResponseEntity.created(URI)
。
Note 2: Don't use printStackTrace()
, use a logger instead.
注意 2:不要使用printStackTrace()
,而是使用记录器。
Provide an @ExceptionHandler
提供一个 @ExceptionHandler
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:
从您的方法中删除 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");
}
}
Note that methods which are annotated with @ExceptionHandler
are allowed to have very flexible signatures. See the Javadocfor details.
请注意,被注解的方法@ExceptionHandler
允许具有非常灵活的签名。有关详细信息,请参阅Javadoc。
回答by Norris
Here is an alternative. Create a generic exception that takes a status code and a message. Then create an exception handler. Use the exception handler to retrieve the information out of the exception and return to the caller of the service.
这是一个替代方案。创建一个带有状态代码和消息的通用异常。然后创建一个异常处理程序。使用异常处理程序从异常中检索信息并返回给服务的调用者。
http://javaninja.net/2016/06/throwing-exceptions-messages-spring-mvc-controller/
http://javaninja.net/2016/06/throwing-exceptions-messages-spring-mvc-controller/
public class ResourceException extends RuntimeException {
private HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
public HttpStatus getHttpStatus() {
return httpStatus;
}
/**
* Constructs a new runtime exception with the specified detail message.
* The cause is not initialized, and may subsequently be initialized by a
* call to {@link #initCause}.
* @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()}
* method.
*/
public ResourceException(HttpStatus httpStatus, String message) {
super(message);
this.httpStatus = httpStatus;
}
}
Then use an exception handler to retrieve the information and return it to the service caller.
然后使用异常处理程序检索信息并将其返回给服务调用者。
@ControllerAdvice
public class ExceptionHandlerAdvice {
@ExceptionHandler(ResourceException.class)
public ResponseEntity handleException(ResourceException e) {
// log exception
return ResponseEntity.status(e.getHttpStatus()).body(e.getMessage());
}
}
Then create an exception when you need to.
然后在需要时创建一个例外。
throw new ResourceException(HttpStatus.NOT_FOUND, "We were unable to find the specified resource.");
回答by Sudabe-Neirizi
return new ResponseEntity<>(GenericResponseBean.newGenericError("Error during the calling the service", -1L), HttpStatus.EXPECTATION_FAILED);
回答by frangel02
Evaluating the error response from another service invocated...
评估来自另一个调用的服务的错误响应...
This was my solution for evaluating the error:
这是我评估错误的解决方案:
try {
return authenticationFeign.signIn(userDto, dataRequest);
}catch(FeignException ex){
//ex.status();
if(ex.status() == HttpStatus.UNAUTHORIZED.value()){
System.out.println("is a error 401");
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
return new ResponseEntity<>(HttpStatus.OK);
}