2017-10-19 73 views
0

我構建了一個Spring REST服務,並且我有一堆通過POST方法接收請求負載的端點。我在我的項目中包含了JSR 303規範,並且它對驗證工作正常。現在我如何讓我的應用程序發送一個JSON響應以及一個不同的狀態碼。目前該應用程序給出了一個400的錯誤頁面。當沒有滿足javax.validation.constraints。*時,發送休息響應而不是HTML頁面

Error from the application

更新:

我想通了,我需要包括BindingResult在我的方法,所以我可以從那裏提取的錯誤。

@PostMapping(value = "/validateBankInformation", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) 
protected ResponseEntity<BusinessSolutionVO> validateBankInformation(@Valid @RequestBody BankInformation bankInformation, BindingResult bindingResult) { 
    if (bindingResult.hasErrors()) { 
     List<ObjectError> errors = bindingResult.getAllErrors(); 
     for (ObjectError error : errors) { 
      System.out.println(error.getDefaultMessage()); 
     } 
    } 
} 
+0

到目前爲止你做了什麼? – delephin

回答

0

實體類是否正確註釋?

您必須在@Table註釋中定義UniqueConstraints

@Table(uniqueConstraints = { @UniqueConstraint(columnNames = { "username" }), 
    @UniqueConstraint(columnNames = { "email" }), @UniqueConstraint(columnNames = { "field1", "field2" }) }) 
public class User implements Serializable { 

    private static final long serialVersionUID = 1L; 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private long id; 

    @Email 
    @NotNull 
    private String email; 

    @NotNull 
    @Size(min = 4, max = 24) 
    private String username; 

    @NotNull 
    private String password; 

    @NotNull 
    private String field1; 

    @NotNull 
    private String field2; 

    // Getters 
    // Setters 
    // Other Methods 

} 
0

有不同的方法可以解決這個問題。但這種情況下,最簡單的一個是返回HTTP錯誤響應象下面這樣:

@PostMapping(value = "/validateBankInformation", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) 
protected ResponseEntity<BusinessSolutionVO> validateBankInformation(@Valid @RequestBody BankInformation bankInformation, BindingResult bindingResult) { 

    if (bindingResult.hasFieldErrors()) { 
      String errors = bindingResult.getFieldErrors().stream() 
        .map(p -> p.getDefaultMessage()).collect(Collectors.joining("\n"));    
       //throw new InvalidRequestParameterException("Bad Request", errors); 

      return ResponseEntity.badRequest().body(errors); 
    } 

    return ResponseEntity.ok("Successful"); 
} 

或者你也可以創建自定義的異常消息,並把他們。

相關問題