Susannah Potts
Susannah Potts

Reputation: 827

Dynamic Error Page from Servlet Response Errors

I'm trying to use the HttpServletResponse function sendError(int,string) to deliver a status code and custom error message to a JSP so I can have a dynamic error page (rather than many specific error pages for each error code/Java exception). However, I can't seem to access the custom message, error type, and stack trace. I can access the URI and Error Code however. I'm sending the error like such:

 response.sendError(HttpServletResponse.SC_BAD_REQUEST,"Some_Message");

I'm trying to get the response in my like this:

 <div class="container">
        <div class="table-responsive">
            <table id="table" class="display">
                <tbody>
                    <tr>
                        <td><b>Error:</b></td>
                        <td>${pageContext.errorData.throwable.cause}</td>
                    </tr>
                    <tr>
                        <td><b>URI:</b></td>
                        <td>${pageContext.errorData.requestURI}</td>
                    </tr>
                        <td><b>Error Message:</b></td>
                        <td>${pageContext.errorData.throwable.message}</td>
                    <tr>
                        <td><b>Status code:</b></td>
                        <td>${pageContext.errorData.statusCode}</td>
                    </tr>
                    <tr>
                        <td><b>Stack trace:</b></td>
                        <td>
                            <c:forEach var="trace" items="${pageContext.errorData.throwable.stackTrace}">
                                <p>${trace}</p>
                            </c:forEach>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

And I have the page descriptor set up like this:

<%@page contentType="text/html" pageEncoding="UTF-8" isErrorPage="true" 
import="java.io.*"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>

EDIT: I should clarify that I know the stacktrace and exception name won't print unless an exception is actually thrown, I'm more interested in having the custom message print as this is useful for debugging issues when they occur after standard testing/deployment procedures.

Upvotes: 1

Views: 1639

Answers (1)

user5243992
user5243992

Reputation: 92

So simply specify the message with request object as attribute, and then access the attribute from the error page

request.setAttribute("err_msg",""Some_Message"");
response.sendError(HttpServletResponse.SC_BAD_REQUEST);

I really cannot remember JSTL, but at the end access the request-scope context, and search for the "err_msg"

Upvotes: 1

Related Questions