0Pricing
Spring Boot 4 Complete Guide · บทเรียน

การตรวจสอบอินพุตและการจัดการข้อผิดพลาด

นำการตรวจสอบข้อมูลสำหรับคำขอขาเข้าไปใช้ และสร้างตัวจัดการข้อยกเว้นส่วนกลางเพื่อจัดการข้อผิดพลาดอย่างมีประสิทธิภาพ

การตรวจสอบอินพุตและการจัดการข้อผิดพลาด เป็นบทเรียน Spring Boot 4 Complete Guide ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Spring Boot 4 Complete Guide และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Spring Boot 4 Complete Guide มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Why Validate API Inputs?

When building RESTful APIs, receiving data from clients is common. But what if that data isn't quite right?

Input validation is the process of ensuring that the data your API receives conforms to expected rules and formats before it's processed. It's crucial for:

  • Data Integrity: Ensuring only valid data enters your system.
  • Security: Preventing malicious inputs (like SQL injection or XSS).
  • Reliability: Avoiding unexpected errors and crashes in your application.

Bean Validation Basics

Spring Boot makes validation easy by integrating with the Jakarta Bean Validation API (JSR 380). This standard provides a set of annotations you can use to define validation rules directly on your data objects.

When Spring processes a request with a validated object, it automatically checks these rules. If any rule is violated, it flags an error.

Common Validation Annotations

Here are some essential Bean Validation annotations you'll often use:

  • @NotNull: Ensures the field is not null.
  • @NotBlank: For strings, ensures it's not null and not just whitespace.
  • @NotEmpty: For strings, collections, or arrays, ensures it's not null and has at least one element/character.
  • @Size(min=X, max=Y): Checks if a string or collection's size is within a range.
  • @Min(value) / @Max(value): Checks if a numeric value is within a range.
  • @Email: Validates if a string is a well-formed email address.
  • @Pattern(regexp): Validates a string against a regular expression.

Creating a Validated DTO

Let's define a simple ProductRequest Data Transfer Object (DTO) that an API might receive. We'll add several validation annotations to its fields.

This DTO represents the expected structure and rules for creating a new product.

package com.coddykit.dto;

import jakarta.validation.constraints.DecimalMin;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;

public class ProductRequest {

    @NotBlank(message = "Name cannot be empty")
    @Size(min = 3, max = 50, message = "Name must be between 3 and 50 characters")
    private String name;

    @NotNull(message = "Price cannot be null")
    @DecimalMin(value = "0.01", message = "Price must be greater than 0")
    private Double price;

    @NotBlank(message = "Description cannot be empty")
    @Size(max = 200, message = "Description cannot exceed 200 characters")
    private String description;

    // Getters and Setters (omitted for brevity in snippet)
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public Double getPrice() { return price; }
    public void setPrice(Double price) { this.price = price; }
    public String getDescription() { return description; }
    public void setDescription(String description) { this.description = description; }
}

Seeing Validation in Action

While Spring handles validation automatically in controllers, you can manually test the Bean Validation API. This program creates a ProductRequest and uses a Validator to check its rules.

Notice how violations are collected!

import com.coddykit.dto.ProductRequest;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();

        ProductRequest invalidProduct = new ProductRequest();
        invalidProduct.setName("  "); // Too short, blank
        invalidProduct.setPrice(-5.0); // Less than 0.01
        invalidProduct.setDescription("Short");

        Set<ConstraintViolation<ProductRequest>> violations =
            validator.validate(invalidProduct);

        if (!violations.isEmpty()) {
            System.out.println("Validation Errors:");
            for (ConstraintViolation<ProductRequest> violation : violations) {
                System.out.println("- " + violation.getMessage());
            }
        } else {
            System.out.println("Product is valid!");
        }
    }
}

Spring Boot's @Valid Integration

In a Spring Boot controller, you activate validation by simply adding the @Valid (or @Validated) annotation to the request body parameter. Spring automatically applies the rules defined in your DTO.

If validation fails, Spring throws a MethodArgumentNotValidException.

package com.coddykit.controller;

import com.coddykit.dto.ProductRequest;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ProductController {

    @PostMapping("/products")
    public ResponseEntity<String> createProduct(@Valid @RequestBody ProductRequest productRequest) {
        // If validation passes, this code executes
        System.out.println("Received valid product: " + productRequest.getName());
        return new ResponseEntity<>("Product created successfully!", HttpStatus.CREATED);
    }
}

Understanding Default Error Handling

When @Valid fails in a controller, Spring Boot's default error handling kicks in. It catches the MethodArgumentNotValidException and returns a 400 Bad Request HTTP status.

The default error response typically includes a detailed (and often verbose) JSON object with error messages, field names, and other technical details. While functional, it might not be the most user-friendly or consistent for your API consumers.

Customizing Error Responses

For a better API experience, you'll want to customize error responses. This means:

  • Consistent Format: All errors look similar.
  • Clear Messages: Easy for clients to understand.
  • Relevant Details: Only provide necessary information.

Spring provides the @ControllerAdvice and @ExceptionHandler annotations to centralize and customize error handling across your entire application.

Building a Global Error Handler

The @ControllerAdvice annotation marks a class that can handle exceptions from any controller. Inside it, @ExceptionHandler methods specify which exceptions to catch and how to respond.

Here's how to create a simple global handler for validation errors, returning a list of specific field errors.

package com.coddykit.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, String>> handleValidationExceptions(
            MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach(error -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
    }
}

Quick Check: Validation & Errors

Which of the following annotations are used to define validation rules for a string field in a DTO, ensuring it's not null, not empty, and has a minimum length?

Recap: Validation & Error Handling

You've learned how to make your Spring Boot APIs robust!

  • Input Validation: Essential for data integrity and security, using the Jakarta Bean Validation API.
  • Validation Annotations: Use @NotBlank, @Size, @Min, @Max, etc., to define rules on your DTOs.
  • @Valid: Triggers validation automatically in your controller methods.
  • Custom Error Handling: Use @ControllerAdvice and @ExceptionHandler to create consistent, user-friendly error responses, especially for MethodArgumentNotValidException.

Next, explore how to handle other types of exceptions in your API!

คำถามที่พบบ่อย

บทเรียน “การตรวจสอบอินพุตและการจัดการข้อผิดพลาด” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การตรวจสอบอินพุตและการจัดการข้อผิดพลาด” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Spring Boot 4 Complete Guide ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Spring Boot 4 Complete Guide มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การตรวจสอบอินพุตและการจัดการข้อผิดพลาด”

นำการตรวจสอบข้อมูลสำหรับคำขอขาเข้าไปใช้ และสร้างตัวจัดการข้อยกเว้นส่วนกลางเพื่อจัดการข้อผิดพลาดอย่างมีประสิทธิภาพ คุณปฏิบัติ Spring Boot 4 Complete Guide ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Spring Boot 4 Complete Guide หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Spring Boot 4 Complete Guide บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “การตรวจสอบอินพุตและการจัดการข้อผิดพลาด” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Spring Boot 4 Complete Guide นี้ได้ไหม

ได้ บทเรียน Spring Boot 4 Complete Guide ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การสร้างคอนโทรลเลอร์ REST
  2. การจัดการคำขอและการตอบกลับ HTTP
  3. การตรวจสอบอินพุตและการจัดการข้อผิดพลาด
  4. การจัดทำเอกสารส่วนเชื่อมต่อ REST ด้วย OpenAPI และ Swagger
← กลับไปที่ Spring Boot 4 Complete Guide