如何在spring mvc @Controller中返回错误信息

我正在使用这样的方法

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

我想在exception发生时返回一些文本消息,但现在我只返回status和null对象。 有可能吗?

正如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块并让它抛出exception。 然后在使用@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 。

这是另一种选择。 创建一个采用状态代码和消息的通用exception。 然后创建一个exception处理程序 使用exception处理程序从exception中检索信息并返回到服务的调用者。

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; } } 

然后使用exception处理程序检索信息并将其返回给服务调用者。

 @ControllerAdvice public class ExceptionHandlerAdvice { @ExceptionHandler(ResourceException.class) public ResponseEntity handleException(ResourceException e) { // log exception return ResponseEntity.status(e.getHttpStatus()).body(e.getMessage()); } } 

然后在需要时创建一个例外。

 throw new ResourceException(HttpStatus.NOT_FOUND, "We were unable to find the specified resource.");