How do you implement a custom error page in Spring Boot?
Answer:
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.