Tutorials Logic, IN info@tutorialslogic.com

Servlet Exception Handling Error Pages, Try Catch, Logging: Causes and Fixes

Mapping Error Types to HTTP Status

A good servlet does not return the same response for every failure. Missing parameters usually mean 400, unauthorized access means 401 or 403, missing resources mean 404, and unexpected server failures mean 500.

  • Use 400 for bad input.
  • Use 404 for missing resources.
  • Use 500 only for unexpected server errors.

Logging Useful Context Safely

Logs should help developers debug without leaking secrets. Include request path, user ID when safe, correlation ID, and exception stack trace. Avoid passwords, tokens, full card numbers, and private form values.

  • Log the exception object.
  • Add request context.
  • Mask sensitive values.

User-Friendly Error Pages

Production users should see helpful error pages, not stack traces. Error pages should explain what happened in plain language and provide navigation back to a safe page.

  • Keep technical details in logs.
  • Show clear next steps.
  • Use web.xml or framework-level mappings.

Servlet Try-Catch with Status

Servlet Try-Catch with Status
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    try {
        String id = request.getParameter("id");
        if (id == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing id");
            return;
        }

        response.getWriter().println("Loading item " + id);
    } catch (Exception ex) {
        log("Failed to load item", ex);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

web.xml Error Page Mapping

web.xml Error Page Mapping
<error-page>
  <error-code>404</error-code>
  <location>/WEB-INF/views/errors/404.jsp</location>
</error-page>

<error-page>
  <exception-type>java.lang.Exception</exception-type>
  <location>/WEB-INF/views/errors/500.jsp</location>
</error-page>

Custom Exception Mapping Idea

Custom Exception Mapping Idea
try {
    productService.load(productId);
} catch (ProductNotFoundException ex) {
    response.sendError(HttpServletResponse.SC_NOT_FOUND, "Product not found");
} catch (ValidationException ex) {
    response.sendError(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage());
} catch (Exception ex) {
    log("Unexpected product error", ex);
    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}

JSP Error Page Directive

JSP Error Page Directive
<%@ page isErrorPage="true" %>
<h1>Something went wrong</h1>
<p>Please try again or contact support if the issue continues.</p>
<a href="${pageContext.request.contextPath}/">Go home</a>
Before you move on

Servlet Exception Handling Error Pages, Try Catch, Logging: Causes and Fixes Mastery Check

4 checks
  • Map expected client, authentication, validation, and server failures to suitable HTTP status codes.
  • Use centralized error handling or container mappings so responses remain consistent across servlets.
  • Log a correlation identifier and safe diagnostic context without exposing stack traces or secrets to users.
  • Handle committed responses, cleanup, forwarding failures, and asynchronous exceptions deliberately.

Servlet Questions Learners Ask

Let a configured error handler or container error page produce the response after the failure is logged.

It exposes implementation details and does not provide a useful recovery message.

No. Once output is committed, the status and headers can no longer be replaced reliably.

Next Step
Next Practice

Finish the concept here, then reinforce it with hands-on coding, interview prep, or a tool that matches the topic.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.