How do you implement a custom error page in Spring Boot?

How do you implement a custom error page in Spring Boot?

A) By creating an HTML file named error.html in the src/main/resources/templates directory
B) By setting custom-error-page=true in application.properties
C) By implementing ErrorController interface
D) Both A and C

Answer:

D) Both A and C

Explanation:

In Spring Boot, you can implement a custom error page by creating an HTML file named error.html in the src/main/resources/templates directory, or by implementing the ErrorController interface to handle errors programmatically.

1. **Using error.html:**

Create an error.html file in the src/main/resources/templates directory. This file will be used as the default error page whenever an error occurs:


<!DOCTYPE html>
<html>
<head>
    <title>Error</title>
</head>
<body>
    <h1>Something went wrong!</h1>
    <p>Sorry, but we encountered an error. Please try again later.</p>
</body>
</html>

2. **Using ErrorController:**

Alternatively, you can create a custom ErrorController by implementing the interface:


import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class CustomErrorController implements ErrorController {

    @RequestMapping("/error")
    public String handleError() {
        return "customError";
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }
}

In this example, the handleError() method returns a custom view named customError, which could be an HTML page or a view template. Implementing the ErrorController interface gives you more control over error handling and allows you to customize the error response further.

Reference links:

Spring Boot Tutorial

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top