@PostMapping("/api/members")
public ResponseEntity<Object> newMember(
@RequestBody @Valid RegisterRequest regReq,
Errors errors) { // Errors 객체를 파라미터로 받지 않으면 validation 실패시 exception 발생
if (errors.hasErrors()) {
String errorCodes = errors.getAllErrors().stream()
.map(error -> error.getCodes()[0])
.collect(Collectors.joining(","));
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(new ErrorResponse("errorCodes = " + errorCodes));
}
}
@RestControllerAdvice("controller")
public class ApiExceptionAdvice {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorResponse> handleBindException(MethodArgumentNotValidException ex) {
String errorMsg= ex.getBindingResult().getAllErrors().stream()
.map(error -> error.getObjectName() + " : " + error.getDefaultMessage() + error.toString())
.collect(Collectors.joining(", "));
return ResponseEntity
.status(HttpStatus.BAD_REQUEST)
.body(new ErrorResponse("errorCodes = " + errorMsg));
}
}