
반응형
springboot 로 RestApi 를 만들다보니 Exception 처리는 필수이다.
한번 해보자.
에러는
{“error”:”에러코드”,”error_decription”:”에러설명”}
위와 같이 내보낼 것이다.
ErrorEnum 정의
@Getter
public enum ErrorEnum {
/* API 응답 코드 */
E00000("00000", "처리 성공", HttpStatus.OK),
E40401("40401", "요청한 엔드포인트가 존재하지 않습니다.", HttpStatus.NOT_FOUND);
E50002("50002", "API 요청 처리 실패.", HttpStatus.INTERNAL_SERVER_ERROR);
private String code;
private String msg;
private HttpStatus status;
private ErrorEnum(String code, String msg, HttpStatus status) {
this.code = code;
this.msg = msg;
this.status = status;
}
}
커스텀 Exception 정의
@SuppressWarnings("serial")
@Getter
public class ApiException extends RuntimeException{
private String errCode;
private String errMsg;
private HttpStatus status;
public ApiException(String s) {
super(s);
}
public ApiException(ErrorEnum e) {
super(e.getMsg());
this.errCode = e.getCode();
this.errMsg = e.getMsg();
this.status = e.getStatus();
}
}
글로벌 Exception 정의
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ApiException.class)
protected ResponseEntity<HashMap> handleCustomException(ApiException e){ //ErrorEnum.E40001
// System.out.println(e.getErrCode() + " / " + e.getErrMsg() + " / " + e.getStatus());
HashMap<String, String> map = new HashMap<String, String>();
map.put("error_description", e.getErrMsg());
map.put("error", e.getErrCode());
return new ResponseEntity<HashMap>(map, e.getStatus());
}
}
Exception 사용하기
controller 에 try 및 throw 설정
// 등록
@PostMapping
public ResponseEntity<User> addUser(@RequestBody User user) throws Exception{
ResponseEntity<User> res;
try {
res = new ResponseEntity<User>(userService.addUser(user), HttpStatus.OK);
} catch (Exception e) {
throw new ApiException(ErrorEnum.E50002);
}
return res;
}
user를 등록하다가 exception이 발생하면 error를 캐치하게 됨
테스트
+ 404 Handler 처리
NoHandlerFoundException 설정
글로벌 Exception 클래스에 추가
@ExceptionHandler(NoHandlerFoundException.class)
protected ResponseEntity<HashMap> handleNoHandlerFoundException(NoHandlerFoundException e,
HttpServletRequest request) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("error_description", ErrorEnum.E40401.getMsg());
map.put("error", ErrorEnum.E40401.getCode());
return new ResponseEntity<HashMap>(map, ErrorEnum.E40401.getStatus());
}
application.properties 설정
spring.mvc.throw-exception-if-no-handler-found: true
spring.web.resources.add-mappings: false
테스트
끝!
반응형
'개발 > Spring' 카테고리의 다른 글
[Spring Cloud] Zipkin(집킨) 분산 추적 해보기 (0) | 2022.10.26 |
---|---|
[Springboot] Sse(Server Send Event) 단방향 통신을 이용해 tail -f 기능 구현 (2) | 2022.10.26 |
[Springboot] kafka JSON 통신하기 (0) | 2022.10.25 |
[Springboot] springBoot와 springCloud 버전 맞추기 (0) | 2022.10.24 |
[Springboot] Maven 멀티 모듈 프로젝트 만들기(Eclipse) (0) | 2022.10.04 |