EthicsComputerCourses
Join training +91 90532 10052

Validation & Error Handling

Spring Boot + React · Lesson 6 of 20 Intermediate 13 min read Updated

By the end of this lesson every StaffDesk error will have one predictable JSON shape. Bad input will name the exact fields that failed, a duplicate email will return 409 Conflict instead of a crash, and the React form will show each message next to its field.

What you should know first: REST Controllers with Spring Boot, where @Valid gave a bare 400, and Spring Data JPA with MySQL or PostgreSQL, where a duplicate email gave a 500. For the annotations themselves, see Validating Request Data and Exception Handling with ProblemDetail in the Spring Boot course. Versions checked: Spring Boot 4.1.2, Spring Framework 7.0.10 and Hibernate Validator 9.1.5, all read from our build.

Two checkpoints, one rule

Think of a passport office in Gurugram. The helper at the gate glances at your form and says "you forgot the photo". But the officer at the counter checks every field again, because anyone can walk past the helper.

React is the helper and Spring Boot is the officer. A request can come from curl, a script or edited JavaScript, so the server always checks. This lesson makes the officer's answer useful, so the helper can show it.

A useful error answer needs three things:

  • The right status code: 400 for bad input, 409 for a clash with existing data, 500 only for real bugs.
  • One body shape for every error, so React needs one piece of code to read them.
  • No internal details: no stack traces, class names or SQL. Those go to the server log.

Step 1: Messages people can read

Bean Validation's default messages, such as "must not be blank", are written for developers. Give each rule a message written for the HR staff who will see it. Update EmployeeRequest:

Java
public record EmployeeRequest(
        @NotBlank(message = "Enter the full name")
        @Size(max = 80, message = "Use at most {max} characters")
        String fullName,

        @NotBlank(message = "Enter a work email")
        @Email(message = "Enter a valid email address")
        @Size(max = 120, message = "Use at most {max} characters")
        String email,

        @NotBlank(message = "Enter a designation")
        @Size(max = 60, message = "Use at most {max} characters")
        String designation,

        @NotNull(message = "Choose a department")
        Long departmentId,

        @NotNull(message = "Enter the joining date")
        @PastOrPresent(message = "Joining date cannot be in the future")
        LocalDate joinedOn) {}

{max} is filled in from the annotation, so the message stays correct if you change the limit. The limits match the column lengths from the JPA lesson (length = 80 and so on). That way the database never sees a value it cannot store.

For Hindi messages later, move the texts into ValidationMessages.properties and write message = "{employee.fullName.required}"; Bean Validation looks the key up per locale.

Step 2: Switch on problem details

RFC 9457 is an internet standard for error bodies in HTTP APIs, called problem details. It replaced RFC 7807 in 2023. Spring Framework has a ProblemDetail class for it, and Spring Boot can use it for all of Spring MVC's own errors with one property. Add it to application.properties:

Properties
# Errors as RFC 9457 problem details
spring.mvc.problemdetails.enabled=true

Restart and send the bad request from the controllers lesson again (empty name, email without @). As before, the Vary and Date headers are left out:

Terminal
curl -i -X POST http://localhost:8080/api/employees -H "Content-Type: application/json" -d '{"fullName":"","email":"meera-at-staffdesk","designation":"QA Engineer","departmentId":1,"joinedOn":"2026-11-02"}'
Output
HTTP/1.1 400
Content-Type: application/problem+json
Connection: close

{"detail":"Invalid request content.","instance":"/api/employees","status":400,"title":"Bad Request"}

The media type is now application/problem+json, and the body uses the standard field names:

FieldMeaningExample
typeA URI that names the kind of problem; left out when it is the default about:blankhttps://staffdesk.example.in/problems/email-taken
titleShort, human summary of that typeEmail already in use
statusThe HTTP status, repeated in the body409
detailExplanation of this one occurrenceAnother employee already uses priya@staffdesk.example.
instanceThe URL that caused it/api/employees

The standard allows extra fields, called extension members. StaffDesk will add one named errors. Spring Boot 4 uses Jackson 3, which wrote the standard fields in alphabetical order in our run. Field order never matters in JSON, so do not depend on it.

The shape is right, but "Invalid request content." still does not say which field failed.

Step 3: One handler for the whole API

A class marked @RestControllerAdvice can handle exceptions thrown by any controller. Spring provides a base class, ResponseEntityExceptionHandler, that already turns every Spring MVC exception into a ProblemDetail. Extend it and change only what you need. Create config/ApiExceptionHandler.java:

Java
@RestControllerAdvice
public class ApiExceptionHandler extends ResponseEntityExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(ApiExceptionHandler.class);

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
            HttpHeaders headers, HttpStatusCode status, WebRequest request) {
        Map<String, String> errors = new TreeMap<>();
        for (FieldError error : ex.getBindingResult().getFieldErrors()) {
            errors.putIfAbsent(error.getField(), error.getDefaultMessage());
        }
        ProblemDetail problem = ex.getBody();
        problem.setType(URI.create("https://staffdesk.example.in/problems/validation"));
        problem.setTitle("Some fields are not valid");
        problem.setDetail("Fix the highlighted fields and try again.");
        problem.setProperty("errors", errors);
        return handleExceptionInternal(ex, problem, headers, status, request);
    }

    @ExceptionHandler(DataIntegrityViolationException.class)
    public ProblemDetail handleConstraint(DataIntegrityViolationException ex) {
        log.warn("Database constraint failed: {}", ex.getMostSpecificCause().getMessage());
        return ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT,
                "The change conflicts with data that already exists.");
    }

    @ExceptionHandler(Exception.class)
    public ProblemDetail handleUnexpected(Exception ex) {
        log.error("Unexpected error", ex);
        return ProblemDetail.forStatusAndDetail(HttpStatus.INTERNAL_SERVER_ERROR,
                "Something went wrong on our side. Please try again.");
    }
}

How it works:

  • handleMethodArgumentNotValid runs when @Valid fails. It collects one message per field into a TreeMap, which keeps the output sorted and stable.
  • setProperty("errors", ...) adds the extension member. React will read it.
  • The two @ExceptionHandler methods are for exceptions that Spring MVC does not know. When several handlers match, Spring picks the most specific exception type, so Exception is only the last resort.
  • Every handler logs the real cause and returns a safe sentence. The browser never sees SQL or a stack trace.

Spring Boot's own problem-details handler steps aside automatically once your class exists, because it is registered only when no ResponseEntityExceptionHandler bean is present. You can leave the property on; it does no harm.

Restart and repeat the bad request, this time with a joining date in the future too:

Output
HTTP/1.1 400
Content-Type: application/problem+json
Connection: close

{"detail":"Fix the highlighted fields and try again.","instance":"/api/employees","status":400,"title":"Some fields are not valid","type":"https://staffdesk.example.in/problems/validation","errors":{"email":"Enter a valid email address","fullName":"Enter the full name","joinedOn":"Joining date cannot be in the future"}}

An empty body, {}, lists all five fields with their "Enter..." or "Choose..." messages. The type URI does not need to open a real page; it is a stable name that clients can compare.

Step 4: 409 for a duplicate email

The JPA lesson ended with a bug: a second employee with an existing email crashed with 500. A duplicate is not a server bug. It is a conflict with existing data, and HTTP has a code for exactly that: 409 Conflict.

First, a specific exception. Spring's ErrorResponseException already carries a ProblemDetail, and the base handler knows how to send it, so a subclass needs no extra handler:

Java
public class EmailTakenException extends ErrorResponseException {

    public EmailTakenException(String email) {
        super(HttpStatus.CONFLICT, problem(email), null);
    }

    private static ProblemDetail problem(String email) {
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT,
                "Another employee already uses " + email + ".");
        problem.setType(URI.create("https://staffdesk.example.in/problems/email-taken"));
        problem.setTitle("Email already in use");
        problem.setProperty("errors", Map.of("email", "This email belongs to another employee"));
        return problem;
    }
}

The errors member uses the same shape as validation errors, so React can show the message beside the email field. Then add two derived queries to EmployeeRepository and check before saving in EmployeeService:

Java
boolean existsByEmailIgnoreCase(String email);

boolean existsByEmailIgnoreCaseAndIdNot(String email, Long id);
Java
@Transactional
public EmployeeResponse create(EmployeeRequest r) {
    if (employees.existsByEmailIgnoreCase(r.email())) {
        throw new EmailTakenException(r.email());
    }
    // ... save as before
}

update uses existsByEmailIgnoreCaseAndIdNot(r.email(), id), so an employee can keep their own email. Note the IgnoreCase: our test used Priya@staffdesk.example with a capital P:

Output
HTTP/1.1 409
Content-Type: application/problem+json

{"detail":"Another employee already uses Priya@staffdesk.example.","instance":"/api/employees","status":409,"title":"Email already in use","type":"https://staffdesk.example.in/problems/email-taken","errors":{"email":"This email belongs to another employee"}}

Why keep the database handler too?

"Check, then insert" has a gap. Two HR staff in Pune and Gurugram could press Save at the same moment, both checks pass, and both inserts run. We tested this by sending ten identical requests in parallel with curl ... &:

Output
201 409 409 409 409 409 409 409 409 409

One request won. Seven were stopped by the service check. Two slipped past the check and were stopped by the database's unique constraint; the server log showed two Database constraint failed: Unique index or primary key violation warnings. Because handleConstraint turns that exception into a 409, the client never saw a 500. The unique constraint is the real guarantee; the friendly check just gives a better message in the common case.

Step 5: Other client errors

The base class already handles the rest of Spring MVC's errors. These are real replies from our run:

RequestStatusdetail
GET /api/employees/abc400Failed to convert 'id' with value: 'abc'
Body that is not valid JSON400Failed to read request
POST with department 9, which does not exist400Unknown department 9
GET /api/nothing-here404No static resource api/nothing-here.
PATCH /api/employees/1405Method 'PATCH' is not supported. (plus an Allow: GET, DELETE, PUT header)

The "Unknown department" row is the ResponseStatusException from the JPA lesson. It is also an ErrorResponseException, so it became a problem detail with no change.

Rules can sit on query parameters too. Since Spring Framework 6.1, putting a constraint directly on a controller parameter turns on method validation, with no extra annotation on the class:

Java
@GetMapping
public List<EmployeeResponse> list(
        @RequestParam(required = false) @Positive Long departmentId) {
    return service.findAll(departmentId);
}

GET /api/employees?departmentId=-1 now returns 400 with "detail":"Validation failure". Note that GET /api/employees/99 still returns 404 with an empty body, exactly as the contract says; ResponseEntity.of never throws.

Step 6: Show the errors in React

The API client from the structure lesson threw a plain Error. Teach it to read problem details. In frontend/src/api/client.js, add an error class and use it when the response is not OK:

JavaScript
export class ApiError extends Error {
  constructor(status, problem) {
    super(problem?.detail || `HTTP ${status}`);
    this.name = "ApiError";
    this.status = status;
    this.problem = problem; // the RFC 9457 body, or null
    this.fieldErrors = problem?.errors || {};
  }
}

// inside apiRequest, replacing the old error lines:
if (!res.ok) {
  const type = res.headers.get("Content-Type") || "";
  const problem = type.includes("application/problem+json") ? await res.json() : null;
  throw new ApiError(res.status, problem);
}

The Content-Type check matters: a 502 from a proxy or an empty 404 has no JSON to read. error.status still works as before.

The form below uses the same idea. A small fake server answers with the exact bodies our API returned, so you can see each case. Submit it as it is, then fix the fields, then try priya@staffdesk.example as the email.

React JSXOpen in editor
import { useState } from "react";
import { createRoot } from "react-dom/client";

// Bodies captured from the real StaffDesk API
const VALIDATION = {"detail":"Fix the highlighted fields and try again.","instance":"/api/employees","status":400,"title":"Some fields are not valid","type":"https://staffdesk.example.in/problems/validation","errors":{"email":"Enter a valid email address","fullName":"Enter the full name"}};
const TAKEN = {"detail":"Another employee already uses priya@staffdesk.example.","instance":"/api/employees","status":409,"title":"Email already in use","type":"https://staffdesk.example.in/problems/email-taken","errors":{"email":"This email belongs to another employee"}};

async function fakeFetch(body) {
  const problem = (status, data) => new Response(JSON.stringify(data),
    { status, headers: { "Content-Type": "application/problem+json" } });
  if (!body.fullName || !body.email.includes("@")) return problem(400, VALIDATION);
  if (body.email.toLowerCase() === "priya@staffdesk.example") return problem(409, TAKEN);
  return new Response(JSON.stringify({ id: 5, ...body }), { status: 201 });
}

function Field({ name, label, value, onChange, error }) {
  return (
    <p>
      <label htmlFor={name}>{label}</label><br />
      <input id={name} value={value} onChange={(e) => onChange(name, e.target.value)}
        aria-invalid={error ? "true" : undefined}
        aria-describedby={error ? name + "-error" : undefined} />
      {error && <span id={name + "-error"} style={{ color: "#a61b1b" }}> {error}</span>}
    </p>
  );
}

function App() {
  const [form, setForm] = useState({ fullName: "", email: "meera-at-staffdesk" });
  const [errors, setErrors] = useState({});
  const [message, setMessage] = useState("");

  const change = (name, value) => setForm((f) => ({ ...f, [name]: value }));

  async function submit(e) {
    e.preventDefault();
    const res = await fakeFetch(form);
    const data = await res.json();
    console.log(res.status, res.headers.get("Content-Type"));
    if (res.ok) {
      setErrors({});
      setMessage(`Saved ${data.fullName} as employee ${data.id}`);
    } else {
      setErrors(data.errors ?? {});
      setMessage(data.detail);
    }
  }

  return (
    <form onSubmit={submit} noValidate style={{ fontFamily: "system-ui, sans-serif" }}>
      <h1>Add employee</h1>
      <Field name="fullName" label="Full name" value={form.fullName} onChange={change} error={errors.fullName} />
      <Field name="email" label="Work email" value={form.email} onChange={change} error={errors.email} />
      <button type="submit">Save</button>
      <p role="status">{message}</p>
    </form>
  );
}

createRoot(document.getElementById("root")).render(<App />);

The first Save shows "Enter the full name" and "Enter a valid email address" beside the two fields, and the console logs 400 application/problem+json. With a name and priya@staffdesk.example, only the email field shows "This email belongs to another employee" and the status line shows the 409 detail. With any other valid email, it reports "Saved ... as employee 5". The error text is linked to its input with aria-describedby, so screen readers read it too. The full form screen comes in Forms, Validation & Errors.

Common mistakes

  • Returning ex.getMessage() to the client. Exception messages can contain SQL, table names or file paths. Log them; send a fixed sentence.
  • Validating only in React. Anyone can skip the form. The server rules are the real ones.
  • Using 500 for a duplicate. A 500 tells monitoring tools the server is broken. A clash with existing data is 409.
  • Relying only on the "exists" check. Two requests can pass it together. Keep the unique constraint and handle DataIntegrityViolationException.

Interview questions

1. What is RFC 9457 and how does Spring support it?

RFC 9457, "Problem Details for HTTP APIs", defines a standard JSON error body with type, title, status, detail and instance, sent as application/problem+json. Spring Framework provides ProblemDetail and ErrorResponseException, and ResponseEntityExceptionHandler turns Spring MVC exceptions into problem details. Spring Boot enables this for MVC with spring.mvc.problemdetails.enabled=true.

2. Why extend ResponseEntityExceptionHandler instead of writing every handler yourself?

It already maps all standard Spring MVC exceptions, such as type mismatches, unreadable bodies and unsupported methods, to the right status and a problem detail. You override only the methods you want to change, like handleMethodArgumentNotValid, and add handlers for your own exceptions.

3. Which status code would you return for a duplicate email, and why not 400?

409 Conflict. The request itself is well formed and passes validation; it fails because of the current state of the data. 400 means the request is malformed or invalid on its own, which helps the client tell "fix your input" from "this clashes with something that exists".

4. Why keep a database unique constraint if the service already checks for duplicates?

The check and the insert are separate steps, so two concurrent requests can both pass the check. Only the database constraint is atomic. The service check gives a friendly message in the normal case, and a handler for DataIntegrityViolationException turns the rare race into the same 409.

Key points

  • React validates to help the user; Spring Boot validates every request because the browser is untrusted.
  • Write messages for users in the annotations; {max} keeps limits and messages in step.
  • Errors use RFC 9457 problem details as application/problem+json; StaffDesk adds an errors map of field messages.
  • One @RestControllerAdvice that extends ResponseEntityExceptionHandler gives every endpoint the same error shape.
  • A duplicate email returns 409 from both the service check and the database constraint handler.
  • Log the real cause on the server; never send stack traces or SQL to the client.

Exercise

Departments need a create endpoint for HR: POST /api/departments with a DepartmentRequest(code, name). The code must be 2 to 10 capital letters (use @Pattern) and the name 2 to 60 characters, each with a readable message. A duplicate code must return 409 with an errors entry for code, using a DepartmentCodeTakenException. Write the record, the exception and the service check, and show the JSON you expect for {"code":"eng","name":"X"}.

Show solution
Java
public record DepartmentRequest(
        @NotBlank(message = "Enter a code")
        @Pattern(regexp = "[A-Z]{2,10}", message = "Use 2 to 10 capital letters")
        String code,

        @NotBlank(message = "Enter a name")
        @Size(min = 2, max = 60, message = "Use {min} to {max} characters")
        String name) {}
Java
public class DepartmentCodeTakenException extends ErrorResponseException {

    public DepartmentCodeTakenException(String code) {
        super(HttpStatus.CONFLICT, problem(code), null);
    }

    private static ProblemDetail problem(String code) {
        ProblemDetail p = ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT,
                "Department code " + code + " already exists.");
        p.setTitle("Department code already in use");
        p.setProperty("errors", Map.of("code", "This code is already used"));
        return p;
    }
}
JSON
{"detail":"Fix the highlighted fields and try again.","instance":"/api/departments","status":400,"title":"Some fields are not valid","type":"https://staffdesk.example.in/problems/validation","errors":{"code":"Use 2 to 10 capital letters","name":"Use 2 to 60 characters"}}

In DepartmentService.create, call a derived query existsByCode(r.code()) and throw the exception before saving. "eng" fails the pattern because it is lower case, and "X" fails only the @Size rule, with {min} and {max} filled in. ApiExceptionHandler needs no change: the new record and exception reuse the same error shape.

Quick Quiz

1. Which Content-Type does a StaffDesk error response use after this lesson?

2. A duplicate email now returns which status?

3. In the parallel test, why did two requests reach the database constraint?

4. What does the catch-all @ExceptionHandler(Exception.class) send to the client?

Learn Spring Boot + React with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call