Skip to content

Commit

Permalink
adding field error validation
Browse files Browse the repository at this point in the history
  • Loading branch information
souravroy committed Jan 17, 2024
1 parent 410c932 commit 7b7c457
Showing 1 changed file with 31 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -1,9 +1,40 @@
package com.homihq.db2rest.exception;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatusCode status, WebRequest request) {
var body = new LinkedHashMap<>();
body.put("type", "https://github.com/kdhrubo/db2rest/invalid-arguments");
body.put("title", "Invalid arguments in the request");
body.put("status", status.value());
var errors = ex.getBindingResult()
.getFieldErrors()
.stream()
.map(error -> Map.of(error.getField(), Objects.requireNonNull(error.getDefaultMessage())))
.toList();
body.put("detail", errors);
body.put("instance", ((ServletWebRequest) request).getRequest().getRequestURI());
body.put("errorCategory", "Invalid-Arguments");
body.put("timestamp", Instant.now());
return new ResponseEntity<>(body, headers, status);
}

}

0 comments on commit 7b7c457

Please sign in to comment.