Spring boot error handling

devKirin·2020년 8월 16일
0

Spring

목록 보기
1/2

Spring boot로 REST API 개발 시 요청 데이터 Validation을 위한 ControllerAdvice의 Exception Handling

  • Request Body가 JSON이며, jackson json을 사용할 때 잘못된 JSON 포맷일 경우
@ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseEntity<Response<Object>> notValidRequestData(HttpServletRequest request, HttpMessageNotReadableException e) {
	if(e.getRootCause() instanceof InvalidFormatException) {
    	// invalid json format
	} else {
    	// another format error
	}
}
  • @Valid Annotation으로 Request 데이터의 Validation이 실패했을 때
 @ExceptionHandler({BindException.class, MethodArgumentNotValidException.class})
    public ResponseEntity<Response<Object>> badRequest(HttpServletRequest request, Exception e) {
    BindingResult bindingResult = null;
	if(e instanceof BindException) {
    	// Validated by @Valid
		bindingResult = ((BindException) e).getBindingResult();
	} else if(e instanceof MethodArgumentNotValidException) {
    	// Validated by @Validated for @RequestParam validatation
		bindingResult = ((MethodArgumentNotValidException)e).getBindingResult();
	}

	if(bindingResult != null) {
		FieldError fieldError = bindingResult.getFieldError();
        // not valid field name
		String fieldName = fieldError.getField();
        // requested value
		Object requestedValue = fieldError.getRejectedValue();
        // if set message on @Valid, it override that setted message.
		String errorMessage = fieldError.getDefaultMessage();
	}
}
  • @RequestParam 등의 요청 데이터의 필드 누락
@ExceptionHandler(MissingServletRequestParameterException.class)
    public ResponseEntity<Response<Object>> badRequestMissingParameter(HttpServletRequest request, MissingServletRequestParameterException e) {
    String parameterName = e.getParameterName();
}
  • 요청된 데이터와 정의된 데이터의 데이터 Type이 다를 경우
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public ResponseEntity<Response<Object>> badRequestInvalidDataParameter(HttpServletRequest request, MethodArgumentTypeMismatchException e) {
	String fieldName = e.getName()
	String definedTypeClass = e.getRequiredType().getName();
	String requestedTypeClass = e.getValue().getClass().getSimpleName();
}
  • @Pattern 등의 Validation 실패
@ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity<Response<Object>> badRequestInvalidParameter(HttpServletRequest request, ConstraintViolationException e) {
    Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        if(constraintViolations != null) {
            for(ConstraintViolation c : constraintViolations) {
            	String pathStr = c.getPropertyPath().toString();
		String[] paths = pathStr.split("\\.");
				String path = paths.length > 0 ? paths[paths.length - 1] : paths[0];
            	String fieldName = c.getPropertyPath()
                Object requestedValue = c.getInvalidValue();
                String message = c.getMessage();
            }
        }
}
profile
Throw hat over the windmill

0개의 댓글