public class DeviceController {
// ...
public void sendShutDown() {
try {
tryToShutDown();
} catch (DeviceShutDownError e) {
logger.log(e);
}
}
private void tryToShutDown() throws DeviceShutDownError {
DeviceHandle handle = getHandle(DEV1);
DeviceRecord record = retrieveDeviceRecord(handle);
pauseDevice(handle);
clearDeviceWorkQueue(handle);
closeDevice(handle);
}
private DeviceHandle getHandle(DeviceId id) {
// ...
throw new DeviceShutDownError("Invalid handle for: " + id.toString());
// ...
}
// ...
}
throw new DeviceShutDownError("Invalid handle for: " + id.toString());
처럼 사용한다.예외를 감싸는 클래스를 만든다
ACMEPort port = new ACMEPort(12);
try {
port.open();
} catch (DeviceResponseException e) {
reportPortError(e);
logger.log("Device response exception", e);
} catch (ATM1212UnlockedException e) {
reportPortError(e);
logger.log("Unlock exception", e);
} catch (GMXError e) {
reportPortError(e);
logger.log("Device response exception", e);
}
LocalPort port = new LocalPort(12);
try {
port.open();
} catch (PortDeviceFailure e) {
reportError(e);
logger.log(e.getMessage(), e);
} finally {
...
}
public class LocalPort {
private ACMEPort innerPort;
public LocalPort(int portNumber) {
innerPort = new ACMEPort(portNumber);
}
public void open() {
try {
innerPort.open();
} catch (DeviceResponseException e) {
throw new PortDeviceFailure(e);
} catch (ATM1212UnlockedException e) {
throw new PortDeviceFailure(e);
} catch (GMXError e) {
throw new PortDeviceFailure(e);
}
}
// ..
}
List<Employee> employees = getEmployees();
if (employee != null) {
for(Employee e : employees) {
totalPay += e.getPay();
}
}
List<Employee> employees = getEmployees();
for(Employee e : employees) {
totalPay += e.getPay();
}
public List<Employee> getEmployees() {
if ( /*.. 직원이 없을 경우 .. */)
return Collections.emptyList();
}
}
UserLevel userLevel = null;
try {
User user = user.Repository.findByUserId(userId);
userLevel = user.getUserLevel();
} catch (UserNotfoundException e) {
userLevel = UserLevel.BASIC;
}
UserLevel userLevel = userService.getuserLevelOrDefault(userId);
public class UserService {
public static final UserLevel USER_BASIC_LEVEL = UsrLevel.BASIC;
public UserLevel getUserLevelOrdefault(Long userId) {
try {
User user = userRepository.findByUserId(userId);
return user.getUserLevel();
} catch(UserNotFoundException e) {
return USER_BASIC_LEVEL;
}
}
}
User user = userRepository.findByUseId(userId);
if (user != null) {
// user를 이용한 처리
}
User user = user.Service.getUserOrElseThrow(userId);
public class UserService {
public static final UserLevel USER_BASIC_LEVEL = UsrLevel.BASIC;
public User getUserOrElseThrow(Long userId) {
User user = userRepository.findByUserId(userId);
if (user == null) {
throw new IllegalArgumentException("User is not found. userId = " + userId)
}
return user;
}
}
}
public class MetricsCalculator {
public double xProjection(Point p1, Point p2) {
return (p2.x - p1.x) * 1.5;
}
}
// calculator.xProjection(null, new Point(12, 13));
// NullPointerException 발생
public class MetricsCalculator {
public double xProjection(Point p1, Point p2) {
if (p1 == null || p2 == null) {
throw InvalidArgumentException("Invalid argument for MetricsCalculator.xProjection");
}
return (p2.x - p1.x) * 1.5;
}
}
public class MetricsCalculator {
public double xProjection(Point p1, Point p2) {
assert p1 != null : "p1 should not be null";
assert p2 != null : "p2 should not be null";
return (p2.x - p1.x) * 1.5;
}
}
public class MyProjectException extends RuntimeException {
private MyErrorCode errorCode;
private String errorMessage;
public MyProjectException(MyErrorCode errorCode) {
//
}
public MyProjectException(MyErrorCode errorCode, String errorMessage) {
//
}
}
public enum MyErrorCode {
private String defaultErrorMessage;
INVALID_REQUEST("잘못된 요청입니다."),
DUPLICATED_REQUEST("기존 요청과 중복되어 처리할 수 없습니다."),
// ...
INTERNAL_SERVER_ERROR("처리 중 에러가 발생했습니다.");
}
//호출부
if (request.getUserName() == null) {
throw new MyProjectException(ErrorCode.INVALID_REQUEST, "userName is null");
}
public class BrokeragePolicyFactory {
public static BrokeragePolicy of(ActionType actionType) {
switch (actionType) {
case RENT:
return new RentBrokeragePolicy();
case PURCHASE:
return new PurchaseBrokeragePolicy();
default:
throw new IllegalArgumentException("해당 actionType에 대한 정책이 존재하지 않습니다.");
}
}
}
public class BrokeragePolicyFactory {
public static BrokeragePolicy of(ActionType actionType) {
switch (actionType) {
case RENT:
return new RentBrokeragePolicy();
case PURCHASE:
return new PurchaseBrokeragePolicy();
default:
throw new HouseUtilsExceptionException(ErrorCode.INVALID_REQUEST, "해당 actionType에 대한 정책이 존재하지 않습니다.");
}
}
}
public classs HouseUtilsException extends RuntimeException {
private ErrorCode errorCode;
private String message;
public HouseUtilsException(ErrorCode errorCode) {
this(errorCode, errorCode.getMessage());
}
public HouseUtilsException(ErrorCode errorCode, String customMessage) {
super(customMessage);
this.errorCode = errorCode;
this.message = customMessage;
}
}
@AllArgsContrustor
// getMessage를 없애고 여기에 @Getter(롬북의 일종)를 붙여도 된다.
public enum ErrorCode {
INVALID_REQUEST("잘못된 요청입니다.");
INTERNAL_ERROR("알 수 없는 에러가 발생했습니다.");
ENTITY_NOT_FOUND("데이터를 찾을 수 없습니다.");
private String message;
private String getMessage() {
return this.message();
}
}
내용 너무 좋아요!