DEV Community

The API Finally Answers Back - Building the REST Layer and One Handler for Every Error

In Part 1 I set out to turn a legacy Java library app into a peer-to-peer platform. In Part 2 I made the persistence real - PostgreSQL, Flyway, tests on the real engine.

But the app still had a problem: it had a solid service layer and a real database, and nothing a client could actually call. Phase 2 fixed that.

And I should be honest about where I started: I had never worked with Spring controllers before. I didn't learn controllers by implementing four of them at once. I learned one - the Catalog controller, done properly, as a guide example - and then generalized the pattern to the rest.

Entities never cross the wire

Before any controller existed, one rule was settled: controllers return thin response records, never JPA entities. The app runs with open-in-view=false and the associations on BookCopy are LAZY, so returning an entity would either serialize a lazy proxy or blow up trying. A record carries exactly what the client needs and nothing it shouldn't see.

The clearest example is the copy response:

public record BookCopyResponse(
  Long id,
  Long bookId,
  Long ownerId,
  CopyVisibility visibility,
  boolean isAvailable,
  BookCondition condition,
  String barcode,
  int timesBorrowed,
  LocalDate acquiredDate
) { }

No owner name, no nested book object - just ids. That closed a lazy-loading caveat that had been hanging over the project since the first review: an earlier design wanted the owner's name in the response, which would have forced a lazy load on every copy serialization. Ids only, and the client asks for the member if it needs the name.

Shipped: four controllers, 44 tests, five PRs

  • Catalog - 22 tests (PR #17): 11 endpoints - create, fetch, search (including title + genre and title + author + genre combinations), copies, availability, archive, and the visibility PATCH. This was the guide example.
  • Member - 7 tests (PR #18): create, fetch by id, fetch by email.
  • Transaction - 10 tests (PR #19): borrow, return, get by id, borrower active/history, all-active, overdue.
  • Discovery - 2 tests (PR #20): the PUBLIC-copy discovery query.
  • Handler - 3 tests (PR #21): the last piece, today.

92 tests when the phase closed (48 β†’ 92 in fifteen days).

Two lessons the tests taught me

1. A query parameter is part of the request.

The Member tests caught me out on this one. Three getMemberByEmail tests were failing - or worse, passing for the wrong reason - because they never sent the email parameter. Spring returns 400 before your service ever runs when a required parameter is missing, so the stub never fires and the test proves nothing about your code.

The fix was one line per test - .param("email", ...) - and the 400 test needed no stub at all, just a verify(never()) that the service was never called. Lesson, now a rule for me: if a test asserts a 400, ask what produced it - the framework, or your code?

2. A route with no test has no proof it exists.

The Discovery controller shipped in PR #17 mapped to /api/v1/dicovery - missing the "s". It survived three merged PRs and 89 tests, because no test had ever called that URL. Reviews passed right around it.

Then I wrote the empty-list test against the real /api/v1/discovery, and it was about to 404 - not because the test was wrong, but because the controller was spelled wrong. The fix was a single letter, and I'd already made it locally before anyone told me it would fail. It shipped with the Discovery tests in PR #20, and "dicovery" is gone from the codebase.

One handler for every error

The other half of Phase 2 is the part clients actually feel: GlobalExceptionHandler, a single @RestControllerAdvice that owns every failure, so all four controllers fail the same way.

Every error body has the same shape:

public record ErrorResponse(
  LocalDateTime timestamp,
  int status,
  String error,
  String message,
  String path
) { }

The families:

  • 404 - not found: missing book, copy, borrower, borrowing, or member.
  • 409 - conflict: duplicate book, copy, or member; already borrowed; unavailable copy; borrow limit exceeded.
  • 400 - business rules: returning a book that was never borrowed, deleting a book with history, archiving a book with an active loan, an invalid copy state.
  • 400 - validation: a bad request body returns the fieldβ†’message map, so the client knows exactly which field failed and why.
  • 400 - Spring's own errors: a type mismatch like GET /catalog/abc, a missing request parameter, an unreadable body - these used to fall into the 500 fallback. Now they land in their own handler:
@ExceptionHandler({ MethodArgumentTypeMismatchException.class, MissingServletRequestParameterException.class, HttpMessageNotReadableException.class })
public ResponseEntity handleSpringBadRequest( Exception ex, HttpServletRequest request) {
  return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ErrorResponse(
    LocalDateTime.now(),
    HttpStatus.BAD_REQUEST.value(),
    "Bad Request",
    ex.getMessage(),
    request.getRequestURI()));
}
  • 500 - the fallback: anything unexpected returns a generic message and gets logged. Never an internal detail, never a stack trace leaking to a client.

The test rule that made the handler tests honest: test the handler through MockMvc, not by calling it directly. @WebMvcTest loads it automatically - you trigger each failure the way a client would and assert the error JSON. The 500 test stubs a plain RuntimeException from the mocked service and asserts the generic message.

And a small trap from the earlier phases still applies: on a success body, $.status is the domain loan status, never the HTTP code - status().isXxx() owns the HTTP code.

What this means in practice

A missing book is a clean 404. A bad body is a structured 400 with field errors. A conflict is a 409, not a stack trace. The API is now something a client - and eventually a real member of this platform - can actually call and understand when it fails.

What this unlocks

I set myself a rule back in October: no freelancing profile updates, no new platforms, until the REST API was complete. That gate is now open. The project is no longer a library only other code can use; it's a platform members can actually call.

What's next

The next chapter isn't decided yet, and I'm not going to invent one for the end of this post. What I will say is what this phase taught me: the boring consistency work - one error shape, one response shape, one test per route - is what turns a collection of endpoints into an API.

If you've built controllers in Spring, what's the first thing you test - the happy path, or the error shape? And have you ever had a typo survive your reviews because nothing actually called the route?

Code, if you want to follow along or tell me what you'd do differently: github.com/Pekins1/LibraryManagementSystem - Rahkel

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.