프로그램에서 발생할 수 있는 에러
런타임 에러
런타임에러는 errors와 exceptions로 나뉜다
Exceptions는 RuntimeException과 다른 예외클래스로 나뉨
public class example {
public static void main(String[] args) {
int number = 100;
int result = 0;
for (int i = 0; i < 10; i++) {
try {
result = number / (int) (Math.random() * 10);
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("0");
}
}
}
}
Exception, ExceptionHandler 만들기
@Data
@Builder
public class ErrorResponse {
private int code;
private String message;
}
public abstract class AbstractException extends RuntimeException{
abstract public int getStatusCode();
abstract public String getMessage();
}
public class TestException extends AbstractException {
@Override
public int getStatusCode() {
return HttpStatus.BAD_REQUEST.value();
}
@Override
public String getMessage() {
return "테스트 예외입니다";
}
}
물론 해당 Exception이 발생하는 클래스에서 try-catch를 써서 할 수 있지만 그렇게 하면 해당 클래스의 기능?분류가 안됨 Exception만 커리하는 클래스를 만들어서 분리하는게 좋음
@Slf4j
@ControllerAdvice
public class CustomExceptionHandler {
@ExceptionHandler(AbstractException.class)
protected ResponseEntity<?> handelCustomExcpetion(AbstractException e){
ErrorResponse error = ErrorResponse.builder()
.message(e.getMessage())
.code(e.getStatusCode())
.build();
return new ResponseEntity<>(error, HttpStatus.resolve(e.getStatusCode()));
}
}