예전챕터에서 에러를 처리하는 Exceptional handler(@Controller Advice)를 배웠을것이다.

당시챕터에선 공통적인 에러처리를 하였지 정상적인 에러처리는 안하였다.


이번엔 헤더값을 가지고 우리가만든 인터셉터로 커스텀익스셉션을 만들어주자

일단 exception이라는 패키지를 만들어주자. 그리고 그안에 CustomException이라는 익스셉션을 만들어주자

 package com.pratice.project.exception;


public class CustomException extends RuntimeException {


private static final long serialVersionUID = 5166839488988493842L;


public CustomException(final String msg){

super(msg);  

}

}


 

 


보면알다시피 에러 메시지를 정의해준다. 그리고 여기서 보시다시피 런타임 익스셉션을 상속받아 

@ControllerAdvice에서 컨트롤 할 수 있게 해주었다.


다음은 인터셉터에서 헤더값을 가지고와서 에러처리를 해주자.

 package com.pratice.project.interceptor;


import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import org.springframework.web.servlet.HandlerInterceptor;

import org.springframework.web.servlet.ModelAndView;


import com.pratice.project.exception.CustomException;


public class CommonInterceptor implements HandlerInterceptor  {



@Override

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object Obj) throws Exception {

// TODO Auto-generated method stub

String id = request.getHeader("id");

if(id!=null&&id.length()>0){

System.out.println("id가 널이 아닙니다! 정상로직!");

}

else if(id==null||id.length()==0){

System.out.println("id가 널입니다! 에러처리!");

throw new CustomException("id가 비어있습니다");

}

return true;

}

@Override

public void postHandle(HttpServletRequest request, HttpServletResponse response, Object Obj, ModelAndView mv)

throws Exception {

// TODO Auto-generated method stub

System.out.println("posthandle");

}

@Override

public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object Obj, Exception ex)

throws Exception {

// TODO Auto-generated method stub

}



}


 


보시다시피 request.getheader값으로 헤더를 가지고오고 id값이 널이아니거나 길이가 0보다크면 정상로직이라고 선언했다.

그것이아니고 id가 널이거나 id길이가 0이면 널처리를 하고throw CustomException으로 넘겨주었다


이 Custom Exception은 ControllerAdvice로 넘어가고


@ExceptionHandler(Exception.class)

public STAT handleException(Exception e) {

STAT stat=new STAT();

stat.setStat("fail");

stat.setCause(e.getMessage());

return stat;

}


위와같은 로직으로 리턴된다. 이제 API를 호출해보자.



에러를 호출할수 있도록 id를 아무값도없이 헤더를 세팅하였다.


다음으로 send를 눌러보자.



보이는가 완벽하게 처리되었다.

이런식으로 커스텀 익스셉션을 처리하면된다.


좀더 커스텀하게하는방법은

ControolerAdvice를 아래와 같이 바꾸면된다.

 package com.pratice.project;


import org.springframework.web.bind.annotation.ControllerAdvice;

import org.springframework.web.bind.annotation.ExceptionHandler;

import org.springframework.web.bind.annotation.RestController;


import com.pratice.project.exception.CustomException;

import com.pratice.project.model.STAT;


@RestController

@ControllerAdvice

public class AnnotationExceptionHandler {

@ExceptionHandler(CustomException.class)

public STAT CustomExceptionhandleException(Exception e) {

STAT stat=new STAT();

stat.setStat("fail");

stat.setCause("커스텀 익스셉션발생!:"+e.getMessage());

return stat;

}

@ExceptionHandler(Exception.class)

public STAT handleException(Exception e) {

STAT stat=new STAT();

stat.setStat("fail");

stat.setCause(e.getMessage());

return stat;

}

}

 


이러면 아래와 같이 확인할 수 있다.




'DEV > SPRING' 카테고리의 다른 글

Rest Service 구현[9]  (0) 2018.05.11
Rest Service 구현[8]  (0) 2018.05.11
Rest Service 구현[7]  (0) 2018.05.11
Rest Service 구현[6]  (0) 2018.05.11
Rest Service 구현[5]  (0) 2018.05.11

+ Recent posts