Avatar
1
Mai Quang Diệu Beginner
Validate Spring boot input
Anh cho em hỏi chút với là với các validate bình thường trong spring boot  em cũng đã validate được rồi nhưng mà với validate mà truyền vào là 1 body thì với input là Integer nhưng em nhập String vào thì nó báo lỗi là Can't parse String to Interger
Nhờ anh chia sẻ giúp em cách để validate hoặc handle exception với trường hợp trên trong spring boot ạ
Em cảm ơn!
  • Answer
spring boot validate
Remain: 5
2 Answers
Avatar
tvd12 Enlightened
tvd12 Enlightened
field:invalid
kiểu này em ạ:
Map&lt;String, String&gt; errors = new HashMap&lt;&gt;()<span>;</span>
Throwable <span>cause</span> = e.getCause()<span>;</span>
if (<span>cause</span> <span>instanceof </span>InvalidFormatException) {
    InvalidFormatException ex = (InvalidFormatException) <span>cause</span><span>;</span>
    for (<span>JsonMappingException.Reference </span>ref : ex.getPath()) {
        errors.put(ref.getFieldName(), <span>"invalid"</span>)<span>;</span>
    }
} else {
    errors.put(<span>"fields"</span>, <span>"invalid"</span>)<span>;</span>
}
return ResponseEntity.<span>badRequest(
</span>    errors
)<span>;</span>
GlobalExceptionHandler@ControllerAdvice
em nhé. Em có hiểu ý anh không hay anh cần viết luôn cả code details?
  • 1
  • Reply
Avatar
InvalidFormatException
thôi ạ. Em cảm ơn anh nhé, để e test thử xem sao.
  • 0
  • Reply
Ok em
 –  tvd12 1659949152000