0
0
SpringbootDebug / FixBeginner · 4 min read

How to Handle 404 Errors in Spring Boot Applications

In Spring Boot, you can handle 404 Not Found errors by creating a custom error page or using @ControllerAdvice with @ExceptionHandler for NoHandlerFoundException. Also, enable spring.mvc.throw-exception-if-no-handler-found=true and disable the default error page to catch 404 errors programmatically.
🔍

Why This Happens

A 404 error occurs when a client requests a URL that does not match any controller or resource in your Spring Boot application. By default, Spring Boot shows a generic error page or JSON response, which might not be user-friendly or customized to your needs.

java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello World";
    }

    // No mapping for /missing-url
}
Output
Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. There was an unexpected error (type=Not Found, status=404). No message available
🔧

The Fix

To handle 404 errors gracefully, configure Spring Boot to throw an exception when no handler is found, then catch that exception with a @ControllerAdvice class. This lets you return a custom response or page.

Also, disable the default error page by setting server.error.whitelabel.enabled=false.

java
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;

@Controller
public class CustomErrorController implements ErrorController {

    @RequestMapping("/error")
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public String handleError() {
        return "custom-404"; // Return view name for 404 page
    }
}

// application.properties
spring.mvc.throw-exception-if-no-handler-found=true
spring.web.resources.add-mappings=false
server.error.whitelabel.enabled=false
Output
When accessing a missing URL, the user sees the custom 404 page instead of the default error page.
🛡️

Prevention

Always define a global error handler using @ControllerAdvice to catch exceptions like NoHandlerFoundException. Enable throwing exceptions for no handler found in your application.properties. This approach helps you control error responses consistently.

Also, create user-friendly error pages for common HTTP errors like 404 and 500 to improve user experience.

java
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ResponseBody
    public String handle404(NoHandlerFoundException ex) {
        return "Custom 404 error: The page you are looking for does not exist.";
    }
}
Output
When a 404 occurs, the response body shows: Custom 404 error: The page you are looking for does not exist.
⚠️

Related Errors

Other common HTTP errors include:

  • 500 Internal Server Error: Caused by exceptions in your code. Handle with @ExceptionHandler(Exception.class).
  • 403 Forbidden: Happens when access is denied. Configure Spring Security to customize this response.
  • 400 Bad Request: Occurs with invalid input. Use validation annotations and handle MethodArgumentNotValidException.

Key Takeaways

Enable spring.mvc.throw-exception-if-no-handler-found=true to catch 404 errors programmatically.
Use @ControllerAdvice with @ExceptionHandler(NoHandlerFoundException.class) to customize 404 responses.
Disable the default whitelabel error page with server.error.whitelabel.enabled=false for custom error handling.
Create user-friendly error pages or messages to improve user experience on 404 errors.
Handle other HTTP errors similarly with global exception handlers for consistent error management.