Spring 如何从rest服务返回错误消息

Spring 如何从rest服务返回错误消息,spring,rest,spring-mvc,spring-rest,Spring,Rest,Spring Mvc,Spring Rest,我已经用Spring boot定义了一个rest服务,它返回一个接口。当服务中发生错误时,如何返回有意义的错误消息?因此,在浏览器上,我显示MyInterface类型的Json 以下代码是控制器调用的服务: public MyInterface getSomeTask() { // business logic here MyInterface myObject= getRelatedClass(); if(myObject == null){ // h

我已经用Spring boot定义了一个rest服务,它返回一个接口。当服务中发生错误时,如何返回有意义的错误消息?因此,在浏览器上,我显示MyInterface类型的Json

以下代码是控制器调用的服务:

public MyInterface getSomeTask() {

    // business logic here
    MyInterface myObject= getRelatedClass();

    if(myObject == null){
       // how to return error message 
    }

    return myObject;
 }

其中一种可能是抛出异常,然后用Spring处理它,这样它将返回正确的json

您可能想看看关于错误处理的文章

您可以创建自定义异常,该异常将抛出到您的逻辑中,然后进行处理:

if(myObject == null){
   throw new CouldNotGetRelatedClassException(); 
}
在控制器中,您可以使用如下错误处理方法:

public class FooController {

   @ExceptionHandler({ CouldNotGetRelatedClassException.class})
   public void handleException() {
       // logic of exception handling
   }

}
另一种方法可能是使用
@ControllerAdvice
注释创建类,该注释将在抛出异常时创建自定义json响应:

@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

   @ExceptionHandler(value = {CouldNotGetRelatedClassException.class})
   protected ResponseEntity<Object> handleNotFound(
     RuntimeException ex, WebRequest request) {
       String bodyOfResponse = "This should be application specific";
       return handleExceptionInternal(ex, bodyOfResponse, 
         new HttpHeaders(), HttpStatus.NOT_FOUND, request);
   }
}
@ControllerAdvice
公共类RestResponseEntityExceptionHandler扩展ResponseEntityExceptionHandler{
@ExceptionHandler(值={CouldNotGetRelatedClassException.class})
未找到受保护的响应句柄(
运行时异常(例如,WebRequest请求){
String bodyOfResponse=“这应该是特定于应用程序的”;
返回手柄内部(例如,响应主体,
新的HttpHeaders(),HttpStatus.NOT_FOUND,request);
}
}

但是,您可能需要注意,错误响应可能与普通对象具有不同的结构,因此您可能希望使用不同的HTTP状态码返回它,以便前端可以确定此消息将以不同的方式反序列化。

谢谢您的回答。但hadleException方法不返回任何内容,所以浏览器如何在屏幕上显示任何json?。将返回类型更改为MyInterface并为MyInterface创建新的实现以在出现异常时返回可能是一个选项。这是应该的方式还是不好的做法?@user1474111我添加了更多的例子