skill/Java.Kotlin

Springboot request param VO class로 받을 시, 필수 값 null일 경우 exception handler 처리

have a nice day :D 2023. 2. 1. 14:17
반응형

Springboot request param VO class로 받을 시, 필수 값 null일 경우 exception handler 처리

RestController

@RequestMapping("/test")
@RestController
public class TestController {

    @GetMapping(value = "/t1")
    public Map<String, Object> t1(
            @Validated ReqVo req) {

Request Param VO


import lombok.Data;
import javax.validation.constraints.NotNull;

@Data
public class ReqVo{
    /**
     * 필수코드 @NotNull 선언
     */
    @NotNull
    String code_type;

Exception Handler

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.*;

@Slf4j
@ControllerAdvice
@RestController
public class RestExceptionHandler  {
	//필수 파라미터 미요청시
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public String handleBindExceptionException(
            BindException ex) {
		// result : Parameter is null : code_type
        return "Parameter is null : " + ex.getFieldError().getField()
    }

	// 기타
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String handleAllExceptions(Exception ex) {
        return ex.getMessage();
    }
}
반응형