Skip to content

Commit

Permalink
feat: ExceptionHandler 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
odo27 committed Sep 4, 2023
1 parent 5d74bc8 commit 3fd091c
Show file tree
Hide file tree
Showing 9 changed files with 64 additions and 33 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package org.apache.coyote.http11;

import static org.apache.coyote.http11.ContentType.TEXT_HTML;

import java.io.IOException;

public class ExceptionHandler {

private static final String RESOURCE_PATH_FORMAT = "static/%s.html";

public HttpResponse handleException(HttpException e) throws IOException {
HttpStatus httpStatus = e.httpStatus();
int code = httpStatus.statusCode();
ResourceLoader resourceLoader = new ResourceLoader();
String body = resourceLoader.loadResourceAsString(String.format(RESOURCE_PATH_FORMAT, code));
return HttpResponse.from(httpStatus, TEXT_HTML, body);
}
}
4 changes: 3 additions & 1 deletion tomcat/src/main/java/org/apache/coyote/http11/FormData.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package org.apache.coyote.http11;

import static org.apache.coyote.http11.HttpStatus.BAD_REQUEST;

import java.util.HashMap;
import java.util.Map;

Expand Down Expand Up @@ -30,6 +32,6 @@ public String get(String key) {
if (formTable.containsKey(key)) {
return formTable.get(key);
}
throw new IllegalArgumentException("데이터가 존재하지 않습니다");
throw new HttpException(BAD_REQUEST, "데이터가 존재하지 않습니다");
}
}
39 changes: 18 additions & 21 deletions tomcat/src/main/java/org/apache/coyote/http11/Http11Processor.java
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
package org.apache.coyote.http11;

import static org.apache.coyote.http11.ContentType.TEXT_CSS;
import static org.apache.coyote.http11.ContentType.TEXT_HTML;
import static org.apache.coyote.http11.HttpMethod.GET;
import static org.apache.coyote.http11.HttpMethod.POST;
import static org.apache.coyote.http11.HttpStatus.BAD_REQUEST;
import static org.apache.coyote.http11.HttpStatus.FOUND;
import static org.apache.coyote.http11.HttpStatus.UNAUTHORIZED;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.URL;
import java.nio.file.Files;
import java.util.Optional;
import java.util.UUID;
import nextstep.jwp.db.InMemoryUserRepository;
Expand Down Expand Up @@ -50,17 +47,23 @@ public void process(final Socket connection) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

HttpRequest httpRequest = HttpRequest.from(bufferedReader);
HttpResponse httpResponse = handleRequest(httpRequest);

outputStream.write(httpResponse.getBytes());
outputStream.write(process(bufferedReader).getBytes());
outputStream.flush();
} catch (IOException | UncheckedServletException e) {
log.error(e.getMessage(), e);
}
}

// [TODO] 예외 처리 하는 exception handler 만들기
private HttpResponse process(BufferedReader bufferedReader) throws IOException {
ExceptionHandler exceptionHandler = new ExceptionHandler();
try {
HttpRequest httpRequest = HttpRequest.from(bufferedReader);
return handleRequest(httpRequest);
} catch (HttpException e) {
return exceptionHandler.handleException(e);
}
}

private HttpResponse handleRequest(HttpRequest httpRequest) throws IOException {
ResourceLoader resourceLoader = new ResourceLoader();

Expand All @@ -75,7 +78,7 @@ private HttpResponse handleRequest(HttpRequest httpRequest) throws IOException {
}
return login(httpRequest);
}
throw new IllegalArgumentException("지원되지 않는 uri 입니다");
throw new HttpException(BAD_REQUEST, "지원되지 않는 uri 입니다");
}
if (httpRequest.method() == GET) {
if (httpRequest.uri().equals("/")) {
Expand All @@ -100,7 +103,7 @@ private HttpResponse handleRequest(HttpRequest httpRequest) throws IOException {
}
return httpResponse;
}
throw new IllegalArgumentException("지원되지 않는 요청입니다");
throw new HttpException(BAD_REQUEST, "지원되지 않는 요청입니다");
}

private HttpResponse register(HttpRequest httpRequest) {
Expand All @@ -109,7 +112,7 @@ private HttpResponse register(HttpRequest httpRequest) {
String password = formData.get("password");
String email = formData.get("email");
if (InMemoryUserRepository.findByAccount(account).isPresent()) {
throw new IllegalStateException("이미 존재하는 아이디입니다. 다른 아이디로 가입해주세요");
throw new HttpException(BAD_REQUEST, "이미 존재하는 아이디입니다. 다른 아이디로 가입해주세요");
}
User user = new User(account, password, email);
InMemoryUserRepository.save(user);
Expand All @@ -122,9 +125,9 @@ private HttpResponse register(HttpRequest httpRequest) {
private HttpResponse loginWithSession(String jsessionid) {
SessionManager sessionManager = new SessionManager();
Session session = sessionManager.findSession(jsessionid)
.orElseThrow(() -> new IllegalArgumentException("잘못된 세션 아이디입니다"));
.orElseThrow(() -> new HttpException(UNAUTHORIZED, "잘못된 세션 아이디입니다"));
session.getAttribute("user")
.orElseThrow(() -> new IllegalArgumentException("세션에 회원정보가 존재하지 않습니다"));
.orElseThrow(() -> new HttpException(UNAUTHORIZED, "세션에 회원정보가 존재하지 않습니다"));
HttpResponse httpResponse = HttpResponse.from(FOUND);
httpResponse.sendRedirect(INDEX_HTML);
return httpResponse;
Expand All @@ -144,7 +147,7 @@ private HttpResponse login(HttpRequest httpRequest) throws IOException {
sessionManager.add(session);
return getRedirectResponseWithCookie(jsessionid);
}
return getUnauthorizedResponse();
throw new HttpException(UNAUTHORIZED, "아이디나 비밀번호를 확인해주세요");
}

private HttpResponse getRedirectResponseWithCookie(String jsessionid) {
Expand All @@ -153,10 +156,4 @@ private HttpResponse getRedirectResponseWithCookie(String jsessionid) {
httpResponse.addCookie(JSESSIONID, jsessionid);
return httpResponse;
}

private HttpResponse getUnauthorizedResponse() throws IOException {
URL resource = getClass().getClassLoader().getResource("static/401.html");
String responseBody = new String(Files.readAllBytes(new File(resource.getFile()).toPath()));
return HttpResponse.from(UNAUTHORIZED, TEXT_HTML, responseBody);
}
}
4 changes: 0 additions & 4 deletions tomcat/src/main/java/org/apache/coyote/http11/HttpCookie.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,6 @@ public void addCookie(String cookieName, String cookieValue) {
cookies.put(cookieName, cookieValue);
}

public boolean isEmpty() {
return cookies.isEmpty();
}

public Optional<String> getCookie(String cookieName) {
if (cookies.containsKey(cookieName)) {
return Optional.of(cookies.get(cookieName));
Expand Down
15 changes: 15 additions & 0 deletions tomcat/src/main/java/org/apache/coyote/http11/HttpException.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package org.apache.coyote.http11;

public class HttpException extends RuntimeException {

private final HttpStatus httpStatus;

public HttpException(HttpStatus httpStatus, String message) {
super(message);
this.httpStatus = httpStatus;
}

public HttpStatus httpStatus() {
return httpStatus;
}
}
8 changes: 3 additions & 5 deletions tomcat/src/main/java/org/apache/coyote/http11/HttpMethod.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package org.apache.coyote.http11;

import static org.apache.coyote.http11.HttpStatus.BAD_REQUEST;

import java.util.Arrays;

public enum HttpMethod {
Expand All @@ -18,10 +20,6 @@ public static HttpMethod from(String methodName) {
return Arrays.stream(HttpMethod.values())
.filter(it -> it.methodName.equals(methodName))
.findAny()
.orElseThrow(() -> new IllegalArgumentException("존재하지 않는 메서드입니다"));
}

public String methodName() {
return methodName;
.orElseThrow(() -> new HttpException(BAD_REQUEST, "존재하지 않는 메서드입니다"));
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package org.apache.coyote.http11;

import static org.apache.coyote.http11.HttpStatus.BAD_REQUEST;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
Expand Down Expand Up @@ -83,7 +85,7 @@ public Optional<String> getCookie(String cookieName) {

public String getBody() {
if (body == null) {
throw new IllegalArgumentException("요청 본문이 존재하지 않습니다");
throw new HttpException(BAD_REQUEST, "요청 본문이 존재하지 않습니다");
}
return body;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ public enum HttpStatus {
OK(200),
FOUND(302),
UNAUTHORIZED(401),
BAD_REQUEST(404),
;

private final int statusCode;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package org.apache.coyote.http11;

import static org.apache.coyote.http11.HttpStatus.BAD_REQUEST;

import java.io.File;
import java.io.IOException;
import java.net.URL;
Expand All @@ -10,7 +12,7 @@ public class ResourceLoader {
public String loadResourceAsString(String path) throws IOException {
URL resource = getClass().getClassLoader().getResource(path);
if (resource == null) {
throw new IllegalArgumentException("요청받은 리소스가 존재하지 않습니다");
throw new HttpException(BAD_REQUEST, "요청받은 리소스가 존재하지 않습니다");
}
return new String(Files.readAllBytes(new File(resource.getFile()).toPath()));
}
Expand Down

0 comments on commit 3fd091c

Please sign in to comment.