Spring Boot Tutorial
Spring Boot - Software Setup and Configuration (STS/Eclipse/IntelliJ)
Prerequisite (Spring Core Concepts)
Spring Boot Core
Spring Boot with REST API
Spring Boot with Database and Data JPA
Spring Boot with Kafka
Spring Boot with AOP
In a typical Spring Boot application, a Service class is responsible for the business logic while the Controller handles HTTP requests and responses. Here, I will provide an example of a Service class that displays response codes and custom error codes.
Let's assume we're building an application that manages user profiles.
Create an enum for your custom error codes:
public enum ErrorCode { USER_NOT_FOUND("ERR001", "User not found"), INVALID_INPUT("ERR002", "Invalid input provided"); private final String code; private final String description; ErrorCode(String code, String description) { this.code = code; this.description = description; } public String getCode() { return code; } public String getDescription() { return description; } }
public class CustomException extends RuntimeException { private final ErrorCode errorCode; public CustomException(ErrorCode errorCode) { super(errorCode.getDescription()); this.errorCode = errorCode; } public ErrorCode getErrorCode() { return errorCode; } }
Let's assume we have a User
entity and a UserRepository
that extends JpaRepository
.
Here's a Service class:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserService { @Autowired private UserRepository userRepository; public User getUserById(Long id) { return userRepository.findById(id).orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND)); } }
You can use Spring's @ControllerAdvice
and @ExceptionHandler
to handle exceptions globally.
import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(CustomException.class) public ResponseEntity<?> handleCustomException(CustomException ex) { // Build a custom error response, here just using a simple string for demonstration String response = ex.getErrorCode().getCode() + ": " + ex.getMessage(); return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); // You can customize the HTTP status based on the error. } }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService; @GetMapping("/{id}") public User getUser(@PathVariable Long id) { return userService.getUserById(id); } }
Now, when you try to fetch a user that doesn't exist (e.g., /users/9999
), the service will throw a CustomException
with an appropriate error code. The global exception handler will then catch this exception and send a response with the custom error code and its description.
Handling HTTP status codes in Spring Boot service:
// Example handling HTTP status codes in Spring Boot service @Service public class MyService { public ResponseEntity<String> processRequest() { // Business logic if (successCondition) { return ResponseEntity.ok("Operation successful"); } else { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Operation failed"); } } }
Custom error messages in Spring Boot service class:
// Example custom error messages in Spring Boot service @Service public class MyService { public String processRequest() { // Business logic if (errorCondition) { throw new RuntimeException("Custom error message"); } return "Operation successful"; } }
Mapping custom error codes in Spring Boot service:
// Example mapping custom error codes in Spring Boot service @Service public class MyService { public String processRequest() { // Business logic if (errorCondition) { throw new CustomException("Custom error code: 1001"); } return "Operation successful"; } }
Displaying response codes in Spring Boot REST services:
// Example displaying response codes in Spring Boot REST service @RestController public class MyController { @Autowired private MyService myService; @GetMapping("/process") public ResponseEntity<String> processRequest() { return myService.processRequest(); } }
Error handling and exception management in Spring Boot service:
// Example error handling in Spring Boot service @Service public class MyService { public String processRequest() { try { // Business logic if (errorCondition) { throw new CustomException("Custom error"); } return "Operation successful"; } catch (CustomException e) { // Log the exception or handle it return "Error: " + e.getMessage(); } } }
Configuring global error handling in Spring Boot service class:
// Example global error handling in Spring Boot service @Service @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(CustomException.class) public ResponseEntity<String> handleCustomException(CustomException ex) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Global Error: " + ex.getMessage()); } }
Logging response codes and errors in Spring Boot:
// Example logging response codes and errors in Spring Boot service @Service public class MyService { private static final Logger logger = LoggerFactory.getLogger(MyService.class); public String processRequest() { try { // Business logic if (errorCondition) { throw new CustomException("Custom error"); } return "Operation successful"; } catch (CustomException e) { // Log the exception logger.error("Error in processRequest(): {}", e.getMessage()); return "Error: " + e.getMessage(); } } }
Defining and using custom error classes in Spring Boot:
// Example defining and using custom error classes in Spring Boot service public class CustomException extends RuntimeException { public CustomException(String message) { super(message); } } @Service public class MyService { public String processRequest() { // Business logic if (errorCondition) { throw new CustomException("Custom error"); } return "Operation successful"; } }