test

Форк
0
Форк от lirfrnk/test
/
ErrorHandlerServlet.java 
97 строк · 3.9 Кб
1
package servlets;
2

3
import java.io.IOException;
4
import java.io.PrintWriter;
5
import java.util.Optional;
6

7
import javax.servlet.RequestDispatcher;
8
import javax.servlet.ServletException;
9
import javax.servlet.http.HttpServlet;
10
import javax.servlet.http.HttpServletRequest;
11
import javax.servlet.http.HttpServletResponse;
12

13
import com.bittercode.constant.ResponseCode;
14
import com.bittercode.model.StoreException;
15
import com.bittercode.model.UserRole;
16
import com.bittercode.util.StoreUtil;
17

18
public class ErrorHandlerServlet extends HttpServlet {
19

20
    public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
21
        PrintWriter pw = res.getWriter();
22
        res.setContentType("text/html");
23

24
        // Fetch the exceptions
25
        Throwable throwable = (Throwable) req.getAttribute("javax.servlet.error.exception");
26
        Integer statusCode = (Integer) req.getAttribute("javax.servlet.error.status_code");
27
        String servletName = (String) req.getAttribute("javax.servlet.error.servlet_name");
28
        String requestUri = (String) req.getAttribute("javax.servlet.error.request_uri");
29
        String errorMessage = ResponseCode.INTERNAL_SERVER_ERROR.getMessage();
30
        String errorCode = ResponseCode.INTERNAL_SERVER_ERROR.name();
31

32
        if (statusCode == null)
33
            statusCode = 0;
34
        Optional<ResponseCode> errorCodes = ResponseCode.getMessageByStatusCode(statusCode);
35
        if (errorCodes.isPresent()) {
36
            errorMessage = errorCodes.get().getMessage();
37
            errorCode = errorCodes.get().name();
38
        }
39

40
        if (throwable != null && throwable instanceof StoreException) {
41
            StoreException storeException = (StoreException) throwable;
42
            if (storeException != null) {
43
                errorMessage = storeException.getMessage();
44
                statusCode = storeException.getStatusCode();
45
                errorCode = storeException.getErrorCode();
46
                storeException.printStackTrace();
47
            }
48
        }
49

50
        System.out.println("======ERROR TRIGGERED========");
51
        System.out.println("Servlet Name: " + servletName);
52
        System.out.println("Request URI: " + requestUri);
53
        System.out.println("Status Code: " + statusCode);
54
        System.out.println("Error Code: " + errorCode);
55
        System.out.println("Error Message: " + errorMessage);
56
        System.out.println("=============================");
57

58
        if (StoreUtil.isLoggedIn(UserRole.CUSTOMER, req.getSession())) {
59
            RequestDispatcher rd = req.getRequestDispatcher("CustomerHome.html");
60
            rd.include(req, res);
61
            StoreUtil.setActiveTab(pw, "home");
62
            showErrorMessage(pw, errorCode, errorMessage);
63

64
        } else if (StoreUtil.isLoggedIn(UserRole.SELLER, req.getSession())) {
65
            RequestDispatcher rd = req.getRequestDispatcher("SellerHome.html");
66
            rd.include(req, res);
67
            StoreUtil.setActiveTab(pw, "home");
68
            showErrorMessage(pw, errorCode, errorMessage);
69

70
        } else {
71
            RequestDispatcher rd = req.getRequestDispatcher("index.html");
72
            rd.include(req, res);
73
            pw.println("<script>"
74
                    + "document.getElementById('topmid').innerHTML='';"
75
                    + "document.getElementById('happy').innerHTML='';"
76
                    + "</script>");
77
            showErrorMessage(pw, errorCode, errorMessage);
78
        }
79

80
    }
81

82
    private void showErrorMessage(PrintWriter pw, String errorCode, String errorMessage) {
83
        pw.println("<div class='container my-5'>"
84
                + "<div class=\"alert alert-success\" role=\"alert\" style='max-width:450px; text-align:center; margin:auto;'>\r\n"
85
                + "  <h4 class=\"alert-heading\">"
86
                + errorCode
87
                + "</h4>\r\n"
88
                + "  <hr>\r\n"
89
                + "  <p class=\"mb-0\">"
90
                + errorMessage
91
                + "</p>\r\n"
92
                + "</div>"
93
                + "</div>");
94

95
    }
96

97
}
98

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.