ErrorCode생성 및 ExceptionHandler로 에러처리
Last updated
Last updated
import lombok.Getter;
@Getter
public enum ErrorCode {
ERROR_SUCCESS(200, "success")
, ERROR_USER(401,"this email is already in use")
....(생략)
private final int code;
private final String msg;
ErrorCode(int code, String msg){
this.code = code;
this.msg = msg;
}
}@Getter
public class ApiException extends RuntimeException {
private final ErrorCode errorCode;
ApiException(ErrorCode errorCode){
this.errorCode = errorCode;
}
}@RestControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler({ApiException.class})
public ResponseEntity handleException(ApiException ex){
Map<String, String> errors = new HashMap<>();
errors.put("error_user_msg", ex.getErrorCode().name());
errors.put("error_code", ex.getErrorCode().getErrorCode()+"");
return ResponseEntity.badRequest().body(errors);
}
}if (user == null)
throw new ApiException(ErrorCode.ERROR_USER);{
"error_code": "410",
"error_user_msg": "ERROR_USER_PASSWORD"
}