How to handle a 404 error in spring boot?

A 404 error occurs when a client requests a URL that does not match any available endpoint or resource in the application. Spring Boot allows us to handle these errors gracefully by providing custom error pages, exception handlers, or a global error handling mechanism.

Key Points: • A 404 error indicates that the requested resource or endpoint does not exist. • Custom error handling improves user experience and provides meaningful responses. • Global exception handling using @ControllerAdvice is the preferred approach for REST APIs.

Example: Suppose a user accesses:

http://localhost:8080/api/products/999

If the endpoint does not exist or the resource cannot be found, Spring Boot returns:

HTTP Status: 404 Not Found

Instead of showing the default error page, we can return a customized response.

Code Example:

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(NoHandlerFoundException.class)
    public ResponseEntity<String> handle404(
            NoHandlerFoundException ex) {

return ResponseEntity .status(HttpStatus.NOT_FOUND)

                .body("Requested resource was not found.");
    }
}

This provides a cleaner and more user-friendly error message.

Alternative Approach:

Create a custom error controller:

@Controller
public class CustomErrorController
        implements ErrorController {

    @RequestMapping("/error")
    public String handleError() {

        return "custom-error-page";
    }
}

This approach is commonly used for web applications using JSP or Thymeleaf.

Custom Error Pages:

Spring Boot automatically detects:

• 404.html • 500.html • error.html

Location:

src/main/resources/templates/

Example:

404.html

Displays a custom page whenever a 404 error occurs.

Enable NoHandlerFoundException:

spring.mvc.throw-exception-if-no-handler-found=true
spring.web.resources.add-mappings=false

This allows Spring Boot to throw exceptions for unmapped URLs.

REST API Best Practice:

Return structured JSON responses:

{ "timestamp": "2026-06-26T10:30:00", "status": 404, "error": "Not Found", "message": "Requested resource was not found", "path": "/api/products/999" }

Benefits: • Easier debugging. • Better API usability. • Consistent error handling.

Real-World Example:

Banking Application:

Request:

GET /accounts/99999

Response:

{ "status": 404, "message": "Account not found" }

This provides meaningful feedback instead of a generic error page.

Interview Tip: A concise interview answer is: In Spring Boot, 404 errors can be handled using custom error pages, ErrorController, or global exception handling with @ControllerAdvice. For REST APIs, returning a structured JSON error response is considered the best practice, while web applications often use custom HTML error pages.