@Getter @Builder
public class ValidExceptionResponse {
private String field;
private String message;
}
@Getter @Builder
public class ExceptionResponse <t> {
private LocalDateTime timestamp;
private String message;
private t details;
}
@RestControllerAdvice
public class MyExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatus status,
WebRequest request) {
List<ValidExceptionResponse> list = new ArrayList<>();
ex.getBindingResult()
.getAllErrors()
.forEach(objectError -> {
FieldError field = (FieldError) objectError;
String message = objectError.getDefaultMessage();
list.add(ValidExceptionResponse.builder()
.field(field.getField())
.message(message)
.build());
});
return new ResponseEntity<>(ExceptionResponse.<List<ValidExceptionResponse>>builder()
.timestamp(LocalDateTime.now())
.message("valid error")
.details(list)
.build(),
HttpStatus.BAD_REQUEST);
}
}
추상 클래스 ResponseEntityExceptionHandler
를 상속받으면 Spring MVC 앱에서 발생하는 예외를 처리할 수 있다.
@Data
@AllArgsConstructor
public class User {
private Integer id;
@Size(min = 2, message = "2글자 이상 입력해주세요.")
private String name;
@Past
private LocalDateTime joinDate;
}
@RestController
@RequiredArgsConstructor
@RequestMapping("/users")
public class UserController {
@PostMapping
public ResponseEntity<User> createUser(@Valid @RequestBody User user) {
User saved = service.save(user);
URI location = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(saved.getId())
.toUri();
return ResponseEntity.created(location).build();
}
}