2015-03-17 9 views
23

Obecnie reakcja na błąd ze startu wiosennej zawiera standardową zawartość jak poniżej:Zmienić domyślny JSON odpowiedź Błąd od wiosny Boot Rest Controller

{ 
    "timestamp" : 1426615606, 
    "exception" : "org.springframework.web.bind.MissingServletRequestParameterException", 
    "status" : 400, 
    "error" : "Bad Request", 
    "path" : "/welcome", 
    "message" : "Required String parameter 'name' is not present" 
} 

szukam sposobu, aby pozbyć się „wyjątek” nieruchomości w odpowiedź. Czy istnieje sposób, aby to osiągnąć?

Odpowiedz

30

Zgodnie z opisem w artykule documentation on error handling można podać własny komponent bean, który implementuje ErrorAttributes, aby przejąć kontrolę nad zawartością.

Łatwym sposobem na to jest podklasa DefaultErrorAttributes. Na przykład:

@Bean 
public ErrorAttributes errorAttributes() { 
    return new DefaultErrorAttributes() { 
     @Override 
     public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) { 
      Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace); 
      // Customize the default entries in errorAttributes to suit your needs 
      return errorAttributes; 
     } 

    }; 
} 
+0

Dzięki za odpowiedź! Próbowałem użyć ErrorAttributes, ale wydaje się, że nie mogę przetestować tej jednostki. Zobacz [http://stackoverflow.com/questions/29120948/unit-testing-a-spring-boot-application-with-custom-errorattributes] Jaki jest pomysł, jak to zrobić? – Marco

Powiązane problemy