2015-03-17 24 views
23

Hiện nay phản ứng lỗi từ khởi động mùa xuân chứa các nội dung tiêu chuẩn như sau:Sửa mặc định JSON lỗi phản hồi từ mùa xuân Boot Nghỉ ngơi điều khiển

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

Tôi đang tìm kiếm một cách để thoát khỏi những "ngoại lệ" bất động sản trong Phản hồi. Có cách nào để đạt được điều này?

Trả lời

30

Như được mô tả trong documentation on error handling, bạn có thể cung cấp hạt của riêng mình triển khai ErrorAttributes để kiểm soát nội dung.

Cách dễ dàng để làm điều đó là phân lớp DefaultErrorAttributes. Ví dụ:

@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

Cảm ơn bạn đã trả lời! Tôi đã cố gắng sử dụng các ErrorAttributes nhưng tôi dường như không thể có được đơn vị này được thử nghiệm. Xem [http://stackoverflow.com/questions/29120948/unit-testing-a-spring-boot-application-with-custom-errorattributes] Bất kỳ ý tưởng nào có thể thực hiện điều này? – Marco

Các vấn đề liên quan