Skip to content
This repository has been archived by the owner on Dec 4, 2024. It is now read-only.

Commit

Permalink
refactor: custom validation response
Browse files Browse the repository at this point in the history
  • Loading branch information
jonasmzsouza committed May 22, 2024
1 parent f338960 commit 38396be
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package br.com.fiap.grupo30.fastfood.adapters.in.rest.exceptions;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class FieldMessage {
private String fieldName;
private String message;
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import java.time.Instant;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

Expand Down Expand Up @@ -74,4 +76,22 @@ public ResponseEntity<StandardError> userCantChangeOrderAfterSubmit(
err.setPath(request.getRequestURI());
return ResponseEntity.status(status).body(err);
}

@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ValidationError> validation(
MethodArgumentNotValidException e, HttpServletRequest request) {
HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
ValidationError err = new ValidationError();
err.setTimestamp(Instant.now());
err.setStatus(status.value());
err.setError("Validation exception");
err.setMessage(e.getMessage());
err.setPath(request.getRequestURI());

for (FieldError f : e.getBindingResult().getFieldErrors()) {
err.addError(f.getField(), f.getDefaultMessage());
}

return ResponseEntity.status(status).body(err);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package br.com.fiap.grupo30.fastfood.adapters.in.rest.exceptions;

import java.util.ArrayList;
import java.util.List;
import lombok.Getter;

@Getter
public class ValidationError extends StandardError {
private final List<FieldMessage> errors = new ArrayList<>();

public void addError(String fieldName, String message) {
errors.add(new FieldMessage(fieldName, message));
}
}

0 comments on commit 38396be

Please sign in to comment.