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

Commit

Permalink
[BE] fix: 클라이언트 요청 오류에 대한 예외 처리 기능 추가 (#176)
Browse files Browse the repository at this point in the history
* fix: 클라이언트 요청 오류에 대한 예외 처리 기능 추가

Co-authored-by: ingpyo <[email protected]>

* refactor: PathVariable에 Valid검증하는 로직 제거

Co-authored-by: ingpyo <[email protected]>

---------

Co-authored-by: echo724 <[email protected]>
  • Loading branch information
ingpyo and echo724 authored Aug 3, 2023
1 parent f022a98 commit a7ff382
Show file tree
Hide file tree
Showing 6 changed files with 97 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
package org.donggle.backend.application.service.request;

public record CategoryAddRequest(String categoryName) {
import jakarta.validation.constraints.NotNull;

public record CategoryAddRequest(
@NotNull(message = "카테고리 이름을 입력해주세요.")
String categoryName
) {
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
package org.donggle.backend.application.service.request;

import jakarta.validation.constraints.NotNull;

import java.util.List;

public record PublishRequest(String publishTo, List<String> tags) {
public record PublishRequest(
@NotNull(message = "블로그를 선택해주세요.")
String publishTo,
List<String> tags
) {
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
package org.donggle.backend.application.service.request;

public record WritingModifyRequest(String title, Long targetCategoryId, Long nextWritingId) {
public record WritingModifyRequest(
String title,
Long targetCategoryId,
Long nextWritingId
) {
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.donggle.backend.ui;

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.donggle.backend.application.service.CategoryService;
import org.donggle.backend.application.service.request.CategoryAddRequest;
Expand All @@ -25,7 +26,7 @@ public class CategoryController {
private final CategoryService categoryService;

@PostMapping
public ResponseEntity<Void> categoryAdd(@RequestBody final CategoryAddRequest request) {
public ResponseEntity<Void> categoryAdd(@Valid @RequestBody final CategoryAddRequest request) {
final Long categoryId = categoryService.addCategory(1L, request);
return ResponseEntity.created(URI.create("/categories/" + categoryId)).build();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.donggle.backend.ui;

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.donggle.backend.application.service.PublishService;
import org.donggle.backend.application.service.WritingService;
Expand Down Expand Up @@ -38,7 +39,7 @@ public ResponseEntity<Void> writingAdd(final MarkdownUploadRequest request) thro
}

@PostMapping("/notion")
public ResponseEntity<Void> writingAdd(@RequestBody final NotionUploadRequest request) {
public ResponseEntity<Void> writingAdd(@Valid @RequestBody final NotionUploadRequest request) {
final Long writingId = writingService.uploadNotionPage(1L, request);
return ResponseEntity.created(URI.create("/writings/" + writingId)).build();
}
Expand Down Expand Up @@ -76,7 +77,7 @@ public ResponseEntity<WritingListWithCategoryResponse> writingListWithCategory(@

@PostMapping("/{writingId}/publish")
public ResponseEntity<Void> writingPublish(@PathVariable final Long writingId,
@RequestBody final PublishRequest request) {
@Valid @RequestBody final PublishRequest request) {
publishService.publishWriting(1L, writingId, request);
return ResponseEntity.ok().build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,19 @@
import org.donggle.backend.exception.notfound.NotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice
Expand Down Expand Up @@ -42,6 +51,71 @@ public ResponseEntity<ErrorResponse> handleIOException(final IOException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse);
}

@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, String>> handleMethodArgumentNotValidException(final MethodArgumentNotValidException e) {
log.warn("Exception from handleMethodArgumentNotValidException = ", e);
final Map<String, String> errors = new HashMap<>();
e.getBindingResult().getAllErrors().forEach((error) -> {
final String fieldName = ((FieldError) error).getField();
final String errorMessage = error.getDefaultMessage();
errors.put(fieldName, errorMessage);
});
return ResponseEntity
.status(HttpStatus.BAD_REQUEST)
.body(errors);
}

@ExceptionHandler(MissingServletRequestParameterException.class)
public ResponseEntity<ErrorResponse> handleMissingServletRequestParameterException(final MissingServletRequestParameterException e) {
log.warn("Exception from handleMissingServletRequestParameterException = ", e);
final ErrorResponse errorResponse = new ErrorResponse(
"잘못된 요청입니다. 누락된 쿼리 파라미터 타입: " + e.getParameterName() +
"예상되는 쿼리 파라미터 타입: " + e.getParameterType()
);
return ResponseEntity
.status(HttpStatus.BAD_REQUEST)
.body(errorResponse);
}

@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public ResponseEntity<ErrorResponse> handleHttpRequestMethodNotSupportedException(final HttpRequestMethodNotSupportedException e) {
log.warn("Exception from handleHttpRequestMethodNotSupportedException = ", e);
final ErrorResponse errorResponse = new ErrorResponse("잘못된 요청입니다. HTTP 메서드를 다시 확인해주세요. 입력한 HTTP 메서드: " + e.getMethod());
return ResponseEntity
.status(HttpStatus.METHOD_NOT_ALLOWED)
.body(errorResponse);
}

@ExceptionHandler(MissingPathVariableException.class)
public ResponseEntity<ErrorResponse> handleMissingPathVariableException(final MissingPathVariableException e) {
log.warn("Exception from handleMissingPathVariableException = ", e);
final ErrorResponse errorResponse = new ErrorResponse("잘못된 요청입니다. 누락된 경로 변수: " + e.getVariableName());
return ResponseEntity
.status(HttpStatus.BAD_REQUEST)
.body(errorResponse);
}

@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public ResponseEntity<ErrorResponse> handleMethodArgumentTypeMismatchException(final MethodArgumentTypeMismatchException e) {
log.warn("Exception from handleMethodArgumentTypeMismatchException = ", e);
final ErrorResponse errorResponse = new ErrorResponse(
"잘못된 요청입니다. 잘못된 변수: " + e.getName() +
"예상되는 변수 타입: " + e.getRequiredType()
);
return ResponseEntity
.status(HttpStatus.BAD_REQUEST)
.body(errorResponse);
}

@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<ErrorResponse> handleHttpMessageNotReadableException(final HttpMessageNotReadableException e) {
log.warn("Exception from handleHttpMessageNotReadableException = ", e);
final ErrorResponse errorResponse = new ErrorResponse("잘못된 요청입니다. 요청 바디를 다시 확인해주세요.");
return ResponseEntity
.status(HttpStatus.BAD_REQUEST)
.body(errorResponse);
}

@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleUnExpectedException(final Exception e) {
log.error("Exception from handleUnExpectedException = ", e);
Expand Down

0 comments on commit a7ff382

Please sign in to comment.