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

Spring Boot - Service Class Example for Displaying Response Codes and Custom Error Codes

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.

1. Define custom error codes:

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;
    }
}

2. Create a custom exception:

public class CustomException extends RuntimeException {
    private final ErrorCode errorCode;

    public CustomException(ErrorCode errorCode) {
        super(errorCode.getDescription());
        this.errorCode = errorCode;
    }

    public ErrorCode getErrorCode() {
        return errorCode;
    }
}

3. Service class:

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));
    }
}

4. Handle the custom exception:

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.
    }
}

5. Using the Service in a Controller:

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.

  1. Handling HTTP status codes in Spring Boot service:

    • Description: Spring Boot provides a way to handle and set HTTP status codes in the service layer. This is useful for indicating the success or failure of an operation.
    • Code:
      // 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");
              }
          }
      }
      
  2. Custom error messages in Spring Boot service class:

    • Description: Customize error messages returned by the service layer to provide meaningful information to clients.
    • Code:
      // 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";
          }
      }
      
  3. Mapping custom error codes in Spring Boot service:

    • Description: Map custom error codes to specific exceptions or conditions in the service layer to differentiate between various error scenarios.
    • Code:
      // 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";
          }
      }
      
  4. Displaying response codes in Spring Boot REST services:

    • Description: Display response codes in Spring Boot REST services to communicate the outcome of the operation to clients.
    • Code:
      // 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();
          }
      }
      
  5. Error handling and exception management in Spring Boot service:

    • Description: Implement error handling and exception management to gracefully handle unexpected errors and provide appropriate responses.
    • Code:
      // 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();
              }
          }
      }
      
  6. Configuring global error handling in Spring Boot service class:

    • Description: Configure global error handling in the service class to centralize error management and apply consistent handling across the application.
    • Code:
      // 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());
          }
      }
      
  7. Logging response codes and errors in Spring Boot:

    • Description: Use logging to capture response codes and errors in Spring Boot services for monitoring and debugging purposes.
    • Code:
      // 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();
              }
          }
      }
      
  8. Defining and using custom error classes in Spring Boot:

    • Description: Define custom error classes to encapsulate error information and create a structured approach to handling errors in the service layer.
    • Code:
      // 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";
          }
      }