# Error Handling

> Backend error handling conventions for Servlet, service, DAO, and MySQL code.

---

## Overview

Servlet controllers are responsible for parameter validation and safe result
return. Services report business failures such as ineligible readers,
unavailable inventory, failed permission checks, and overdue-rule violations.
DAOs report database failures without leaking SQL details to JSP pages.

---

## Controller Behavior

- Validate required parameters, numeric IDs, dates, and operation names before
  calling services.
- On validation failure, return to the relevant JSP with field-level messages
  or redirect with a short flash-style message.
- Do not print stack traces or database details into JSP output.
- Use forwards for rendering request-scoped form errors and redirects after
  successful mutating operations to avoid duplicate submissions.

---

## Service Behavior

- Centralize business rule failures in the service layer: permission denied,
  reader not eligible to borrow, book not available, renewal rejected, overdue
  status conflicts, and inventory update failures.
- Keep transaction rollback decisions close to multi-step workflows such as
  borrow, return, renew, and book intake.
- Return clear success/failure results or throw project-specific exceptions
  once the application defines an exception model.

---

## DAO Behavior

- Wrap low-level SQL/MySQL exceptions with enough context for logs, but do not
  expose credentials, raw SQL with user values, or stack traces to users.
- Close JDBC resources reliably using the project helper or language construct
  chosen by the first implementation.
- Let services decide whether a DAO failure should abort a transaction or map
  to a user-facing message.

---

## User-Facing Results

Use concise messages suitable for JSP rendering. For protected operations,
prefer generic denial messages over exposing permission internals.

For this application, messages rendered into JSP pages should be Simplified
Chinese. This includes `ServiceResult.message`, field-level validation errors,
flash messages set by Servlet controllers, and display names returned by entity
helpers. Keep log-only diagnostics, exception types, stored enum codes, request
parameter names, and database values unchanged unless a separate contract change
requires it.
