Exception Handling SpringBoot
Exception Handling SpringBoot
@ExceptionHandler(NoHandlerFoundException.class)
public String handleNotFoundError(Model model) {
System.out.println("No handler found exception");
String errorMessage = "OOops! Something went
wrong - value passed via exception handler.";
model.addAttribute("errorMessage", errorMessage);
return "error"; // This will display the "error.html"
Thymeleaf template
}
@ExceptionHandler(CustomException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ER
ROR)
@ResponseBody
public ErrorResponse
handleCustomException(CustomException ex) {
// This will return the response in JSON format
return new ErrorResponse("An error occurred: " +
ex.getMessage());
}
}
Error.html
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Error Page</title>
<!-- Add your CSS styles and other assets here -->
</head>
<body>
<div>
<!-- Use Thymeleaf expression ${errorMessage} to
display the error message -->
<h1 th:text="${errorMessage}">OOops! Something
went wrong - default message.</h1>
<p>We apologize for the inconvenience. The requested
page is not available at the moment.</p>
<!-- You can add more helpful information or links to
guide users -->
</div>
</body>
</html>
When the CustomException is encountered, the JSON
response will be sent to the user in the case of
the browser as well as in the case of the Postman.
When NoHandlerFoundException is encountered,
the error.html template will be displayed to the user in the
case of the browser. In the case of the Postman, the
HTML page content will be returned to the user.
Second Approach:
in case of 404 errors, the JSON response was displayed in the browser as well as in the case of
the postman. If you want to display a custom HTML Error Page when users encounter unmapped
or erroneous URLs, this is how it can be done:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
pom.xml
Step-2: Create error.html Page
Create an error page named error.html in
the src/main/resources/templates directory:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Error Page</title>
<!-- Add your CSS styles and other assets here -->
</head>
<body>
<div>
<h1>Oops! Something went wrong</h1>
<p>We apologize for the inconvenience. The requested page is not
available at the moment.</p>
<!-- You can add more helpful information or links to guide users -->
</div>
</body>
</html>